キー コンテナーに非対称キーを格納する

非対称秘密キーは、ローカル コンピューターにそのまま平文として保存しないでください。 秘密キーを格納する必要がある場合は、キー コンテナーを使用します。 キー コンテナーの詳細については、「コンピューター レベルおよびユーザー レベルの RSA キー コンテナーについて」を参照してください。

Note

この記事のコードは Windows に適用されます。また、.NET Core 2.2 以前のバージョンでは使用できない機能を使用しています。 詳細については、dotnet/runtime#23391の記事を参照してください。

非対称キーを作成し、キー コンテナーに格納する

  1. CspParameters クラスの新しいインスタンスを作成し、キー コンテナーを呼び出すときに使用する名前を CspParameters.KeyContainerName フィールドに渡します。

  2. AsymmetricAlgorithm クラス (通常は RSACryptoServiceProvider または DSACryptoServiceProvider) から派生するクラスの新しいインスタンスを作成し、以前に作成した CspParameters オブジェクトをそのコンストラクターに渡します。

注意

非対称キーの作成と取得は 1 つの操作です。 キーがまだコンテナーにない場合は、返される前に作成されます。

キー コンテナーからキーを削除する

  1. CspParameters クラスの新しいインスタンスを作成し、キー コンテナーを呼び出すときに使用する名前を CspParameters.KeyContainerName フィールドに渡します。

  2. AsymmetricAlgorithm クラス (通常は RSACryptoServiceProvider または DSACryptoServiceProvider) から派生するクラスの新しいインスタンスを作成し、以前に作成した CspParameters オブジェクトをそのコンストラクターに渡します。

  3. AsymmetricAlgorithm から派生するクラスの RSACryptoServiceProvider.PersistKeyInCsp または DSACryptoServiceProvider.PersistKeyInCsp プロパティを false (Visual Basic では False) に設定します。

  4. AsymmetricAlgorithm から派生したクラスの Clear メソッドを呼び出します。 このメソッドは、クラスのすべてのリソースを解放し、キー コンテナーを消去します。

非対称キーを作成し、それをキー コンテナーへ格納し、後でキーを取得し、最後にキー コンテナーからキーを削除する方法の例を次に示します。

GenKey_SaveInContainer メソッドと GetKeyFromContainer メソッドのコードは類似していることに注意してください。 CspParameters オブジェクトのキー コンテナー名を指定した場合、AsymmetricAlgorithm プロパティまたは PersistKeyInCsp プロパティを true に設定して、指定したキー コンテナーを PersistKeyInCsp オブジェクトに渡すと、動作は次のようになります。

  • 指定した名前のキー コンテナーが存在しない場合、コンテナーが作成されてキーが保持されます。
  • 指定した名前のキー コンテナーが存在する場合、そのコンテナー内のキーが現在の AsymmetricAlgorithm オブジェクトに自動的に読み込まれます。

つまり、最初に実行される GenKey_SaveInContainer メソッドのコードはこのキーを保持し、2 番目に実行される 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.

関連項目