共用方式為


將對稱金鑰儲存在金鑰容器中

非對稱私密金鑰不應逐字或以純文字儲存到本機電腦上。 如果您需要儲存私密金鑰,請使用金鑰容器。 如需金鑰容器的詳細資訊,請參閱了解電腦層級和使用者層級的 RSA 金鑰容器

注意

本文中的程式碼適用於 Windows,並使用 .NET Core 2.2 和舊版無法使用的功能。 如需詳細資訊,請參閱 dotnet/runtime#23391 (英文)

建立非對稱金鑰並儲存到金鑰容器中

  1. 建立 CspParameters 類別的新執行個體,並將您為金鑰容器命名的名稱傳遞至 CspParameters.KeyContainerName 欄位。

  2. 建立衍生自 AsymmetricAlgorithm 類別的新執行個體 (通常是 RSACryptoServiceProviderDSACryptoServiceProvider),並將先前建立的 CspParameters 物件傳遞至其建構函式。

注意

建立和擷取非對稱金鑰是一項作業。 如果在容器中不存在金鑰,則會在傳回之前建立金鑰。

從金鑰容器中刪除金鑰

  1. 建立 CspParameters 類別的新執行個體,並將您為金鑰容器命名的名稱傳遞至 CspParameters.KeyContainerName 欄位。

  2. 建立衍生自 AsymmetricAlgorithm 類別的新執行個體 (通常是 RSACryptoServiceProviderDSACryptoServiceProvider),並將先前建立的 CspParameters 物件傳遞至其建構函式。

  3. 將衍生自 AsymmetricAlgorithm 的類別 RSACryptoServiceProvider.PersistKeyInCspDSACryptoServiceProvider.PersistKeyInCsp 屬性設定為 false (即 Visual Basic 中的False)。

  4. 呼叫從 AsymmetricAlgorithm 衍生類別的 Clear 方法。 這個方法會釋放該類別的所有資源,並清除金鑰容器。

範例

下列範例示範如何建立非對稱金鑰、將金鑰儲存到金鑰容器中、在稍後擷取金鑰,以及從容器中刪除金鑰。

請注意,GenKey_SaveInContainer 方法和 GetKeyFromContainer 方法中的程式碼很類似。 當您為 CspParameters 物件指定金鑰容器名稱,並傳遞至 AsymmetricAlgorithm 屬性或 PersistKeyInCsp 屬性設定為 truePersistKeyInCsp 物件時,將進行下列行為:

  • 如果指定名稱的金鑰容器不存在,則會建立一個金鑰容器並保存金鑰。
  • 如果指定名稱的金鑰容器存在,則會將容器中的金鑰自動載入目前的 AsymmetricAlgorithm 物件中。

因此,GenKey_SaveInContainer 方法中的程式碼因為先執行,所以會保存金鑰,而 GetKeyFromContainer 方法中的程式碼因為後執行,所以會載入金鑰。

Imports System
Imports System.Security.Cryptography

Public Class StoreKey

    Public Shared Sub Main()
        Try
            ' Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer")

            ' Retrieve the key from the container.
            GetKeyFromContainer("MyKeyContainer")

            ' Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer")

            ' Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer")

            ' Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer")
        Catch e As CryptographicException
            Console.WriteLine(e.Message)
        End Try
    End Sub

    Private Shared Sub GenKey_SaveInContainer(ByVal ContainerName As String)
        ' Create the CspParameters object and set the key container
        ' name used to store the RSA key pair.
        Dim parameters As New CspParameters With {
            .KeyContainerName = ContainerName
        }

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container MyKeyContainerName.
        Using rsa As New RSACryptoServiceProvider(parameters)
            ' Display the key information to the console.
            Console.WriteLine($"Key added to container:  {rsa.ToXmlString(True)}")
        End Using
    End Sub

    Private Shared Sub GetKeyFromContainer(ByVal ContainerName As String)
        ' Create the CspParameters object and set the key container
        '  name used to store the RSA key pair.
        Dim parameters As New CspParameters With {
            .KeyContainerName = ContainerName
        }

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container MyKeyContainerName.
        Using rsa As New RSACryptoServiceProvider(parameters)
            ' Display the key information to the console.
            Console.WriteLine($"Key retrieved from container : {rsa.ToXmlString(True)}")
        End Using
    End Sub

    Private Shared Sub DeleteKeyFromContainer(ByVal ContainerName As String)
        ' Create the CspParameters object and set the key container
        '  name used to store the RSA key pair.
        Dim parameters As New CspParameters With {
            .KeyContainerName = ContainerName
        }

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container.
        ' Delete the key entry in the container.
        Dim rsa As New RSACryptoServiceProvider(parameters) With {
            .PersistKeyInCsp = False
        }

        ' Call Clear to release resources and delete the key from the container.
        rsa.Clear()

        Console.WriteLine("Key deleted.")
    End Sub
End Class
using System;
using System.Security.Cryptography;

public class StoreKey
{
    public static void Main()
    {
        try
        {
            // Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer");

            // Retrieve the key from the container.
            GetKeyFromContainer("MyKeyContainer");

            // Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer");

            // Create a key and save it in a container.
            GenKey_SaveInContainer("MyKeyContainer");

            // Delete the key from the container.
            DeleteKeyFromContainer("MyKeyContainer");
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
    }

    private static void GenKey_SaveInContainer(string containerName)
    {
        // Create the CspParameters object and set the key container
        // name used to store the RSA key pair.
        var parameters = new CspParameters
        {
            KeyContainerName = containerName
        };

        // Create a new instance of RSACryptoServiceProvider that accesses
        // the key container MyKeyContainerName.
        using var rsa = new RSACryptoServiceProvider(parameters);

        // Display the key information to the console.
        Console.WriteLine($"Key added to container: \n  {rsa.ToXmlString(true)}");
    }

    private static void GetKeyFromContainer(string containerName)
    {
        // Create the CspParameters object and set the key container
        // name used to store the RSA key pair.
        var parameters = new CspParameters
        {
            KeyContainerName = containerName
        };

        // Create a new instance of RSACryptoServiceProvider that accesses
        // the key container MyKeyContainerName.
        using var rsa = new RSACryptoServiceProvider(parameters);

        // Display the key information to the console.
        Console.WriteLine($"Key retrieved from container : \n {rsa.ToXmlString(true)}");
    }

    private static void DeleteKeyFromContainer(string containerName)
    {
        // Create the CspParameters object and set the key container
        // name used to store the RSA key pair.
        var parameters = new CspParameters
        {
            KeyContainerName = containerName
        };

        // Create a new instance of RSACryptoServiceProvider that accesses
        // the key container.
        using var rsa = new RSACryptoServiceProvider(parameters)
        {
            // Delete the key entry in the container.
            PersistKeyInCsp = false
        };

        // Call Clear to release resources and delete the key from the container.
        rsa.Clear();

        Console.WriteLine("Key deleted.");
    }
}

輸出如下所示:

Key added to container:
<RSAKeyValue> Key Information A</RSAKeyValue>
Key retrieved from container :
<RSAKeyValue> Key Information A</RSAKeyValue>
Key deleted.
Key added to container:
<RSAKeyValue> Key Information B</RSAKeyValue>
Key deleted.

另請參閱