Partilhar via


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

Chaves privadas assimétricas nunca devem ser armazenadas literalmente ou 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 recipientes de chave, consulte Entendendo recipientes de chaves RSA em nível de usuário e em nível de máquina.

Para criar uma chave assimétrica e salve-o em um recipiente de chave

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

  2. Criar uma nova instância de uma classe que deriva do AsymmetricAlgorithm classe (geralmente RSACryptoServiceProvider ou DSACryptoServiceProvider) e passe criada anteriormente CspParameters objeto ao seu construtor.

Para excluir uma chave de um recipiente de chave

  1. Criar uma nova instância de um CspParameters classe e passar o nome que você deseja chamar o recipiente de chave para o CspParameters.KeyContainerName campo.

  2. Criar uma nova instância de uma classe que deriva do AsymmetricAlgorithm classe (geralmente RSACryptoServiceProvider ou DSACryptoServiceProvider) e passe criada anteriormente CspParameters objeto ao seu construtor.

  3. Definir o PersistKeyInCSP a propriedade da classe que deriva de AsymmetricAlgorithm para false (False em Visual Basic).

  4. Chamar o Clear método da classe que deriva de AsymmetricAlgorithm. Este método libera todos os recursos da classe e limpa o recipiente de chave.

Exemplo

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

Observe que o código de GenKey_SaveInContainer método e a GetKeyFromContainer método é semelhante. Quando você especificar um nome de recipiente de chave para um CspParameters de objeto e passá-lo para um AsymmetricAlgorithm de objeto com o PersistKeyInCsp propriedade ou PersistKeyInCsp propriedade é definida como true, ocorrerá o seguinte. Se um recipiente de chave com o nome especificado não existir, então um é criado e a chave é persistente. Se existe um contêiner de chave com o nome especificado, a chave no recipiente é carregada automaticamente no atual AsymmetricAlgorithm objeto. Portanto, o código a GenKey_SaveInContainer método persiste a chave porque ele é executado primeiro, enquanto o código na 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.");
    }
}
      

Consulte também

Conceitos

A geração de chaves de criptografia e descriptografia

Criptografia de dados

Descriptografar dados

Serviços de criptografia

Outros recursos

Tarefas de criptografia