Share via


Menyimpan kunci asimetris dalam kontainer kunci

Kunci privat asimetris tidak boleh disimpan secara verbatim atau dalam teks biasa di komputer lokal. Jika Anda perlu menyimpan kunci privat, gunakan kontainer kunci. Untuk informasi selengkapnya tentang kontainer utama, lihat Memahami kontainer kunci RSA tingkat komputer dan tingkat pengguna.

Catatan

Kode dalam artikel ini berlaku untuk Windows dan menggunakan fitur yang tidak tersedia di .NET Core 2.2 dan versi sebelumnya. Untuk informasi selengkapnya, lihat dotnet/runtime#23391.

Membuat kunci asimetris dan menyimpannya dalam kontainer kunci

  1. Buat instans baru dari kelas CspParameters dan berikan nama yang Anda inginkan untuk kontainer kunci ke bidang CspParameters.KeyContainerName.

  2. Buat instans baru kelas yang berasal dari kelas AsymmetricAlgorithm (biasanya RSACryptoServiceProvider atau DSACryptoServiceProvider) dan teruskan objek CspParameters yang dibuat sebelumnya ke konstruktornya.

Catatan

Pembuatan dan pengambilan kunci asimetris adalah satu operasi. Jika kunci belum ada di kontainer, kunci tersebut dibuat sebelum dikembalikan.

Menghapus kunci dari kontainer kunci

  1. Buat instans baru dari kelas CspParameters dan berikan nama yang Anda inginkan untuk kontainer kunci ke bidang CspParameters.KeyContainerName.

  2. Buat instans baru kelas yang berasal dari kelas AsymmetricAlgorithm (biasanya RSACryptoServiceProvider atau DSACryptoServiceProvider) dan teruskan objek CspParameters yang dibuat sebelumnya ke konstruktornya.

  3. Atur properti RSACryptoServiceProvider.PersistKeyInCsp atau DSACryptoServiceProvider.PersistKeyInCsp dari kelas yang berasal dari AsymmetricAlgorithm ke false (False dalam Visual Basic).

  4. Panggil metode Clear dari kelas yang berasal dari AsymmetricAlgorithm. Metode ini melepaskan semua sumber daya kelas dan membersihkan kontainer kunci.

Contoh

Contoh berikut menunjukkan cara membuat kunci asimetris, menyimpannya dalam kontainer kunci, mengambil kunci di lain waktu, dan menghapus kunci dari kontainer.

Perhatikan bahwa kode dalam metode GenKey_SaveInContainer dan metode GetKeyFromContainer serupa. Saat Anda menentukan nama kontainer kunci untuk objek CspParameters dan meneruskannya ke objek AsymmetricAlgorithm dengan properti PersistKeyInCsp atau properti PersistKeyInCsp yang diatur ke true, perilakunya adalah sebagai berikut:

  • Jika kontainer kunci dengan nama yang ditentukan tidak ada, maka akan dibuat satu kunci dan kunci dipertahankan.
  • Jika kontainer kunci dengan nama yang ditentukan memang ada, maka kunci dalam kontainer secara otomatis dimuat ke dalam objek AsymmetricAlgorithm saat ini.

Oleh karena itu, kode dalam metode GenKey_SaveInContainer mempertahankan kunci karena dijalankan terlebih dahulu, sementara kode dalam metode GetKeyFromContainer memuat kunci karena ini adalah eksekusi kedua.

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

Outputnya sebagai berikut:

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.

Lihat juga