Condividi tramite


Archiviare chiavi asimmetriche in un contenitore di chiavi

Le chiavi private asimmetriche non devono essere mai archiviate in modalità verbatim o in testo normale nel computer locale. Se occorre archiviare una chiave privata, è opportuno usare un contenitore di chiavi. Per altre informazioni sui contenitori di chiavi, vedere Riconoscimento dei contenitori di chiavi RSA a livello di computer e utente.

Nota

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 classe CspParameters e passare il nome da usare per chiamare il contenitore di chiavi al campo CspParameters.KeyContainerName.

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

Nota

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

Eliminare la chiave da un contenitore di chiavi

  1. Creare una nuova istanza di una classe CspParameters e passare il nome da usare per chiamare il contenitore di chiavi al campo CspParameters.KeyContainerName.

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

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

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

Esempio

Il seguente esempio illustra come creare una chiave asimmetrica, salvarla in un contenitore di chiavi, recuperare la chiave in un secondo momento ed eliminarla dal contenitore.

Si noti che il codice del metodo GenKey_SaveInContainer è simile a quello del metodo GetKeyFromContainer. Quando si specifica un nome di contenitore di chiavi per un oggetto CspParameters e lo si passa a un oggetto AsymmetricAlgorithm con la proprietà PersistKeyInCsp o con la proprietà PersistKeyInCsp impostata su true, si verifica quanto segue:

  • Se un contenitore di chiavi con il nome specificato non esiste, ne sarà creato uno e la chiave sarà resa persistente.
  • Se esiste un contenitore di chiavi con il nome specificato, la chiave nel contenitore sarà caricata automaticamente nell'oggetto AsymmetricAlgorithm corrente.

Il codice nel metodo GenKey_SaveInContainer rende quindi permanente la chiave poiché è eseguito per primo, mentre il codice nel metodo GetKeyFromContainer carica la chiave poiché è eseguito per secondo.

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.

Vedi anche