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

非對稱私密金鑰不應逐字或以純文字儲存到本機電腦上。 如果您需要儲存私密金鑰,請使用金鑰容器。 如需金鑰容器的詳細資訊,請參閱 瞭解電腦層級和使用者層級的 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.

另請參閱