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

更新 : 2007 年 11 月

非対称秘密キーは、ローカル コンピュータにそのまま平文として保存しないでください。秘密キーを格納する必要がある場合は、キー コンテナを使用することをお勧めします。キー コンテナの詳細については、プラットフォーム SDK ドキュメント (https://www.microsoft.com/japan/msdn) の「CryptoAPI」セクションを参照してください。

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

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

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

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

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

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

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

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

使用例

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

GenKey_SaveInContainer メソッド内および GetKeyFromContainer メソッド内のコードは類似していることに注意してください。CspParameters オブジェクトのキー コンテナの名前を指定した場合、PersistKeyInCsp プロパティと共に、または PersistKeyInCsp プロパティを true に設定して、指定したキー コンテナを AsymmetricAlgorithm オブジェクトに渡すと、次のような処理が行われます。指定した名前のキー コンテナが存在しない場合、コンテナが作成されてキーが保持されます。指定した名前のキー コンテナが存在する場合、そのコンテナ内のキーが現在の AsymmetricAlgorithm オブジェクトに自動的に読み込まれます。つまり、最初に実行される GenKey_SaveInContainer メソッド内のコードはこのキーを保持し、2 番目に実行される GetKeyFromContainer メソッド内のコードはこのキーを読み込みます。

Imports System
Imports System.IO
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

    Public 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 cp As New CspParameters()
        cp.KeyContainerName = ContainerName

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container MyKeyContainerName.
        Dim rsa As New RSACryptoServiceProvider(cp)

        ' Display the key information to the console.
        Console.WriteLine("Key added to container:  {0}", rsa.ToXmlString(True))
    End Sub

    Public 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 cp As New CspParameters()
        cp.KeyContainerName = ContainerName

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container MyKeyContainerName.
        Dim rsa As New RSACryptoServiceProvider(cp)

        ' Display the key information to the console.
        Console.WriteLine("Key retrieved from container : {0}", rsa.ToXmlString(True))
    End Sub

    Public 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 cp As New CspParameters()
        cp.KeyContainerName = ContainerName

        ' Create a new instance of RSACryptoServiceProvider that accesses
        ' the key container.
        Dim rsa As New RSACryptoServiceProvider(cp)

        ' Delete the key entry in the container.
        rsa.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.IO;
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);
        }

    }

    public static void GenKey_SaveInContainer(string ContainerName)
    {
        // Create the CspParameters object and set the key container 
        // name used to store the RSA key pair.
        CspParameters cp = new CspParameters();
        cp.KeyContainerName = ContainerName;

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

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

    public static void GetKeyFromContainer(string ContainerName)
    {
        // Create the CspParameters object and set the key container 
        // name used to store the RSA key pair.
        CspParameters cp = new CspParameters();
        cp.KeyContainerName = ContainerName;

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

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

    public static void DeleteKeyFromContainer(string ContainerName)
    {
        // Create the CspParameters object and set the key container 
        // name used to store the RSA key pair.
        CspParameters cp = new CspParameters();
        cp.KeyContainerName = ContainerName;

        // Create a new instance of RSACryptoServiceProvider that accesses
        // the key container.
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);

        // Delete the key entry in the container.
        rsa.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.

参照

概念

暗号化と復号化のためのキーの生成

データの暗号化

データの復号化

その他の技術情報

暗号タスク

暗号サービス