Condividi tramite


Archiviare chiavi asimmetriche in un contenitore di chiavi

Le chiavi private asimmetriche non devono mai essere archiviate verbatim o in chiaro nel computer locale. Se è necessario archiviare una chiave privata, usare un contenitore di chiavi. Per altre informazioni sui contenitori chiave, vedere Informazioni sui contenitori di chiavi RSA a livello di computer e a livello di utente.

Annotazioni

Il codice in questo articolo si applica a Windows e usa funzionalità non disponibili in .NET Core 2.2 e versioni precedenti. Per altre informazioni, vedere dotnet/runtime#23391.

Creare una chiave asimmetrica e salvarla in un contenitore di chiavi

  1. Creare una nuova istanza di una CspParameters classe e passare il nome che si vuole chiamare il contenitore di chiavi al CspParameters.KeyContainerName campo.

  2. Creare una nuova istanza di una classe che deriva dalla AsymmetricAlgorithm classe (in genere RSACryptoServiceProvider o DSACryptoServiceProvider) e passare l'oggetto creato CspParameters in precedenza al relativo costruttore.

Annotazioni

La creazione e il recupero di una chiave asimmetrica è un'operazione. Se una chiave non è già presente nel contenitore, viene creata prima di essere restituita.

Eliminare la chiave dal contenitore di chiavi

  1. Creare una nuova istanza di una CspParameters classe e passare il nome che si vuole chiamare il contenitore di chiavi al CspParameters.KeyContainerName campo.

  2. Creare una nuova istanza di una classe che deriva dalla AsymmetricAlgorithm classe (in genere RSACryptoServiceProvider o DSACryptoServiceProvider) e passare l'oggetto creato CspParameters in precedenza al relativo costruttore.

  3. Impostare la proprietà RSACryptoServiceProvider.PersistKeyInCsp o DSACryptoServiceProvider.PersistKeyInCsp della classe che deriva da AsymmetricAlgorithm su false (False in Visual Basic).

  4. Chiamare il Clear metodo della classe che deriva da AsymmetricAlgorithm. Questo metodo rilascia tutte le risorse della classe e cancella il contenitore di chiavi.

Esempio

Nell'esempio seguente viene illustrato come creare una chiave asimmetrica, salvarla in un contenitore di chiavi, recuperare la chiave in un secondo momento ed eliminare la chiave dal contenitore.

Si noti che il codice nel GenKey_SaveInContainer metodo e nel GetKeyFromContainer metodo sono simili. Quando si specifica un nome contenitore di chiavi per un CspParameters oggetto e lo si passa a un AsymmetricAlgorithm oggetto con la PersistKeyInCsp proprietà o PersistKeyInCsp la proprietà impostata su true, il comportamento è il seguente:

  • Se non esiste un contenitore di chiavi con il nome specificato, ne viene creato uno e la chiave viene salvata in modo permanente.
  • Se esiste un contenitore di chiavi con il nome specificato, la chiave nel contenitore viene caricata automaticamente nell'oggetto corrente AsymmetricAlgorithm .

Di conseguenza, il codice nel GenKey_SaveInContainer metodo rende persistente la chiave perché viene eseguita per prima, mentre il codice nel GetKeyFromContainer metodo carica la chiave perché viene eseguita la seconda.

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.");
    }
}

L'output è il seguente:

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.

Vedere anche