Практическое руководство. Хранение асимметричных ключей в контейнере ключей

Асимметричные закрытые ключи никогда не должны храниться в распечатанном виде или в виде простого текста на локальном компьютере. Если необходимо хранить закрытый ключ, следует использовать для этого контейнер ключа. Сведения о контейнерах ключей см. в разделе Основные сведения о контейнерах ключей RSA уровня компьютера и уровня пользователя.

Создание асимметричного ключа и сохранение его в контейнере ключа

  1. Создайте новый экземпляр класса CspParameters и задайте желаемое название контейнера ключа в поле CspParameters.KeyContainerName.

  2. Создайте новый экземпляр класса, производного от класса AsymmetricAlgorithm (обычно это RSACryptoServiceProvider или DSACryptoServiceProvider), и передайте соответствующему конструктору ранее созданный объект CspParameters.

Удаление ключа из контейнера ключа

  1. Создайте новый экземпляр класса CspParameters и задайте желаемое название контейнера ключа в поле CspParameters.KeyContainerName.

  2. Создайте новый экземпляр класса, производного от класса AsymmetricAlgorithm (обычно это RSACryptoServiceProvider или DSACryptoServiceProvider), и передайте его конструктору ранее созданный объект CspParameters.

  3. Присвойте свойству PersistKeyInCSP класса, производного от AsymmetricAlgorithm, значение false (False в Visual Basic).

  4. Выполните вызов метода Clear класса, производного от AsymmetricAlgorithm. Указанный метод освобождает все ресурсы класса и удаляет контейнер ключа.

Пример

В следующем примере показано, как создать асимметричный ключ, сохранить его в контейнере ключа, извлечь ключ из контейнера, а также удалить ключ из контейнера ключа.

Обратите внимание, что код метода GenKey_SaveInContainer аналогичен коду метода GetKeyFromContainer. При указании имени контейнера ключа для объекта CspParameters и передаче его объекту AsymmetricAlgorithm со свойством PersistKeyInCsp или PersistKeyInCsp, установленным в значение true, происходит следующее. Если контейнер ключа с заданным именем не существует, то происходит его создание и ключ сохраняется. Если контейнер ключа с заданным именем существует, то ключ, содержащийся в контейнере, автоматически загружается в текущий объект AsymmetricAlgorithm. Поэтому, код метода GenKey_SaveInContainer сохраняет ключ, поскольку он выполняется раньше, чем код метода 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.");
    }
}
      

См. также

Основные понятия

Создание ключей для шифрования и расшифровки

Шифрование данных

Расшифровка данных

Службы криптографии

Другие ресурсы

Задачи криптографии