다음을 통해 공유


Generating Keys for Encryption and Decryption

Creating and managing keys is an important part of the cryptographic process. Symmetric algorithms require the creation of a key and an initialization vector (IV) that must be kept secret from anyone who should not decrypt your data. Asymmetric algorithms require the creation of a public key and a private key. The public key can be made public to anyone, while the private key must known only by the party who will decrypt the data encrypted with the public key. This section describes how to generate and manage keys for both symmetric and asymmetric algorithms.

Symmetric Keys

The symmetric encryption classes supplied by the .NET Framework require a key and a new IV to encrypt and decrypt data. Whenever you create a new instance of one of the managed symmetric cryptographic classes using the default constructor, a new key and IV are automatically created. Anyone whom you want to be able to decrypt your data must possess the same key and IV and use the same encryption algorithm. Generally, a new key and IV should be created for every session, and neither the key nor IV should be stored for use in a later session.

To communicate a symmetric key and IV to a remote party, you would usually encrypt the symmetric key and IV using asymmetric encryption. Sending these values across an insecure network without encrypting them is extremely unsafe, as anyone that intercepts these values has the ability to decrypt your data. For more information on this process of encrypting and transferring the key and IV, see Creating a Cryptographic Scheme.

The following example shows the creation of a new instance of the TripleDESCryptoServiceProvider class that implements the TripleDES algorithm.

Dim TDES As TripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider()
[C#]
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();

When the previous code is executed, a new key and IV are generated and placed in the Key and IV properties, respectively.

Sometimes you might need to generate multiple keys. In this situation, you can create a new instance of a class that implements a symmetric algorithm and then create a new key and IV by calling the GenerateKey and GenerateIV methods. The following code example illustrates how to create new keys and IVs after a new instance of the asymmetric cryptographic class has been made.

Dim TDES As TripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider()
TDES.GenerateIV()
TDES.GenerateKey()
[C#]
TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();
TDES.GenerateIV();
TDES.GenerateKey();

When the previous code is executed, a key and IV are generated when the new instance of TripleDESCryptoServiceProvider is made. Another key and IV are created when the GenerateKey and GenerateIV methods are called.

Asymmetric Keys

The .NET Framework provides the RSACryptoServiceProvider and DSACryptoServiceProvider classes for asymmetric encryption. These classes create a public/private key pair when you use the default constructor to create a new instance. Asymmetric keys can be either stored for use in multiple sessions or generated for one session only. While the public key can be made generally available, the private key should be closely guarded.

A public/private key pair is generated whenever a new instance of an asymmetric algorithm class is created. Once a new instance of the class is created, the key information can be extracted using one of two methods:

Both methods accept a Boolean value that indicates whether to return only the public key information or to return both the public-key and the private-key information. An RSACryptoServiceProvider class can be initialized to the value of an RSAParameters structure by using the ImportParameters method.

The following code example creates a new instance of the RSACryptoServiceProvider class, creating a public/private key pair, and saves the public key information to an RSAParameters structure.

'Generate a public/private key pair.
Dim RSA as RSACryptoServiceProvider = new RSACryptoServiceProvider()
'Save the public key information to an RSAParameters structure.
Dim RSAKeyInfo As RSAParameters = RSA.ExportParameters(false)
[C#]
//Generate a public/private key pair.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//Save the public key information to an RSAParameters structure.
RSAParameters RSAKeyInfo = RSA.ExportParameters(false);

Storing Asymmetric Keys in a Key Container

Asymmetric private keys should never be stored verbatim or in plain text on the local computer. If you need to store a private key, you should use a key container. For more information on key containers, see the CryptoAPI section in the Platform SDK documentation at https://msdn.microsoft.com.

To create an asymmetric key and save it in a key container

  1. Create a new instance of a CspParameters class and pass the name that you want to call the key container to the CspParameters.KeyContainerName field.
  2. Create a new instance of a class that derives from the AsymmetricAlgorithm class (usually RSACryptoServiceProvider or DSACryptoServiceProvider) and pass the previously created CspParameters object to its constructor.

To delete a key from a key container

  1. Create a new instance of a CspParameters class and pass the name that you want to call the key container to the CspParameters.KeyContainerName field.
  2. Create a new instance of a class that derives from the AsymmetricAlgorithm class (usually RSACryptoServiceProvider or DSACryptoServiceProvider) and pass the previously created CspParameters object to its constructor.
  3. Set the PersistKeyInCSP property of the class that derives from AsymmetricAlgorithm to false (False in Visual Basic).
  4. Call the Clear method of the class that derives from AsymmetricAlgorithm. This method releases all resources of the class and clears the key container.

The following example demonstrates how to create an asymmetric key, save it in a key container, retrieve the key at a later time, and delete the key from the container.

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
[C#]
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.");
    }
}

When the previous example is run, the following is displayed to the console.

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.

See Also

Encrypting Data | Decrypting Data | Cryptographic Tasks | Cryptographic Services