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

非對稱私密金鑰不應逐字或以純文字儲存到本機電腦上。 如果您需要儲存私密金鑰,請使用金鑰容器。 如需金鑰容器的詳細資訊,請參閱 瞭解機器層級和使用者層級 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. RSACryptoServiceProvider.PersistKeyInCsp將 衍生自 AsymmetricAlgorithm 的 類別的 或 DSACryptoServiceProvider.PersistKeyInCsp 屬性設定為 false Visual Basic) False 中的 (。

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

範例

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

請注意,GenKey_SaveInContainer 方法和 GetKeyFromContainer 方法中的程式碼很類似。 當您指定物件的索引鍵容器名稱 CspParameters ,並將它 AsymmetricAlgorithm 傳遞給屬性或 PersistKeyInCsp 屬性設定 true 為 的物件 PersistKeyInCsp 時,行為如下所示:

  • 如果指定名稱的金鑰容器不存在,則會建立一個金鑰容器並保存金鑰。
  • 如果指定名稱的金鑰容器存在,則會將容器中的金鑰自動載入目前的 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.

另請參閱