방법: 키 컨테이너에 비대칭 키 저장

업데이트: 2007년 11월

비대칭 개인 키는 로컬 컴퓨터에 그대로 또는 일반 텍스트로 저장되어서는 안 됩니다. 개인 키를 저장해야 하는 경우에는 키 컨테이너를 사용해야 합니다. 키 컨테이너에 대한 자세한 내용은 https://www.microsoft.com/korea/msdn. 있는 Platform SDK 설명서의 CryptoAPI 단원을 참조하십시오.

비대칭 키를 만들어서 키 컨테이너에 저장하려면

  1. CspParameters 클래스의 새 인스턴스를 만들고 키 컨테이너에 지정할 이름을 CspParameters.KeyContainerName 필드에 전달합니다.

  2. AsymmetricAlgorithm 클래스에서 파생된 클래스의 새 인스턴스(일반적으로 RSACryptoServiceProvider 또는 DSACryptoServiceProvider)를 만들고, 이전에 만든 CspParameters 개체를 이 개체의 생성자에 전달합니다.

키 컨테이너에서 키를 삭제하려면

  1. CspParameters 클래스의 새 인스턴스를 만들고 키 컨테이너에 지정하고 싶은 이름을 CspParameters.KeyContainerName 필드에 전달합니다.

  2. Asymmetric Algorithm 클래스에서 파생된 클래스의 새 인스턴스(일반적으로 RSACryptoServiceProvider 또는 DSACryptoServiceProvider)를 만들고, 이전에 만든 CspParameters 개체를 이 개체의 생성자에 전달합니다.

  3. AsymmetricAlgorithm에서 파생된 클래스의 PersistKeyInCSP 속성을 false(Visual Basic에서는 False)로 설정합니다.

  4. AsymmetricAlgorihtm에서 파생된 클래스의 Clear 메서드를 호출합니다. 이 메서드는 클래스의 모든 리소스를 해제하고 키 컨테이너를 지웁니다.

예제

다음 예제에서는 비대칭 키를 만들어서 키 컨테이너에 저장하고, 나중에 이 키를 검색해서 키 컨테이너에서 삭제하는 방법을 보여 줍니다.

GenKey_SaveInContainer 메서드와 GetKeyFromContainer 메서드의 코드는 비슷합니다. CspParameters 개체에 키 컨테이너 이름을 지정하고 PersistKeyInCsp 속성 또는 PersistKeyInCsp 속성이 true로 설정된 AsymmetricAlgorithm 개체에 전달하면 다음과 같은 결과가 발생합니다. 지정한 이름의 키 컨테이너가 없으면 해당 키 컨테이너가 만들어지고 키가 유지됩니다. 지정한 이름의 키 컨테이너가 있으면 키 컨테이너의 키가 자동으로 현재 AsymmetricAlgorithm 개체에 로드됩니다. 따라서 GenKey_SaveInContainer 메서드의 코드는 먼저 실행되므로 키를 유지하고, GetKeyFromContainer 메서드의 코드는 두 번째로 실행되므로 키를 로드합니다.

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.

참고 항목

개념

암호화 및 해독용 키 생성

데이터 암호화

데이터 해독

기타 리소스

암호화 작업

암호화 서비스