Share via


Como: Armazenar Chaves Asssimétricas em um Contêiner de Chaves

Chaves privadas assimétricas nunca devem ser armazenadas literalmente ou em texto sem formatação no computador local.Se você precisar armazenar uma chave particular, você deve usar um contêiner de chave.Para obter mais informações sobre os recipientes de chave, consulte a seção CryptoAPI na documentação do plataforma SDK em https://msdn.microsoft.com.

Para criar uma chave assimétrica e salvá-lo em um contêiner de chave

  1. Criar uma nova instância de um CspParameters classe e passar o nome que você deseja chamar o contêiner de chave para o CspParameters.KeyContainerNamecampo.

  2. Criar uma nova instância de uma classe que deriva de AsymmetricAlgorithm classe (normalmente RSACryptoServiceProvider or DSACryptoServiceProvider) e passar a criada anteriormenteCspParameters objeto ao seu construtor.

Para excluir uma chave de um contêiner de chave

  1. Criar uma nova instância de um CspParameters classe e o nome que você deseja passar telefonar o contêiner de chave à CspParameters.KeyContainerName campo.

  2. Criar uma nova instância de uma classe que deriva de AsymmetricAlgorithm classe (geralmente RSACryptoServiceProvider or DSACryptoServiceProvider) e passar a criada anteriormenteCspParameters objeto ao seu construtor.

  3. conjunto o PersistKeyInCSP propriedade da classe que deriva de AsymmetricAlgorithm to False (False no Visual Basic).

  4. Chamar o desmarcar método da classe que deriva de AsymmetricAlgorithm.Esse método libera todos os recursos da classe e limpa o contêiner de chave.

Exemplo

O exemplo a seguir demonstra como criar uma chave assimétrica, salvá-lo em um recipiente de chave, recuperar a chave, mais tarde e exclua a chave do contêiner.

Observe que que código no GenKey_SaveInContainer método e o GetKeyFromContainer método é semelhante. Quando você especificar um nome de contêiner de chave para um CspParameters objeto e passá-lo para um AsymmetricAlgorithm objeto com o PersistKeyInCsp propriedade ou PersistKeyInCsp conjunto de propriedades como true, ocorre o seguinte. Se um contêiner de chave com o nome especificado não existir, em seguida, um é criado e a chave é persistente.Se um contêiner de chave com o nome especificado existir, e no contêiner de chave é carregada automaticamente para o corrente AsymmetricAlgorithm objeto. Portanto, o código a GenKey_SaveInContainer método persiste a chave porque ele é executado primeiro, enquanto o código a GetKeyFromContainer método carrega a chave porque ele é executado em segundo.

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.

Consulte também

Conceitos

Gerando chaves de criptografia e descriptografia

Criptografando dados

Descriptografar dados

Outros recursos

Tarefas de criptografia

Serviços de criptografia