Creating and managing keys is an important part of the encryption process. SymmetricAlgorithmRequires the creation of keys and Initialization vectors (iv) that must be kept confidential to anyone who should not decrypt the data ). An asymmetric algorithm requires the creation of a public key and a private key. The public key can be made public to anyone, and the private key must be known only to the party that wants to decrypt the data encrypted with the public key. This section describes how to generate and manage keys for symmetric and asymmetric algorithms.
Symmetric Key
The symmetric encryption class provided by. NET Framework requires a key and a new IV to encrypt and decrypt data. Each time a new instance hosting a symmetric encryption class is created using the default constructor, a new key and IV are automatically created. No matter who you want to decrypt your data, he or she must have the same key and IV and use the same encryption algorithm. Generally, new keys and IV should be created for each session, and neither key nor IV should be stored for later sessions.
To transmit symmetric keys and IV to remote users, asymmetric encryption is usually used to encrypt symmetric keys and IV. It is extremely insecure to encrypt these values by sending them over an insecure network because anyone who intercepts these values can decrypt your data. For more information about the encryption and transmission key and IV processes, see create an encryption scheme.
The following example shows how to create a new instance of the tripledescryptoserviceprovider class that implements the tripledes algorithm.
[Visual Basic]Dim TDES as tripledescryptoserviceprovider = new tripledescryptoserviceprovider ()[C #]Tripledescryptoserviceprovider TDES = new tripledescryptoserviceprovider ();
The precedingCodeThe new key and IV are generated and placed inKeyAndIVAttribute.
Sometimes you may need to generate multiple keys. In this case, you can create a new instance of the class that implements symmetric algorithms, and then callGeneratekeyAndGenerateivMethod to create a new key and IV. The following code example illustrates how to create a new key and IV after creating a new instance of the asymmetric encryption class.
[Visual Basic]Dim TDES as tripledescryptoserviceprovider = new tripledescryptoserviceprovider () TDES. generateiv () TDES. generatekey ()[C #]Tripledescryptoserviceprovider TDES = new tripledescryptoserviceprovider (); TDES. generateiv (); TDES. generatekey ();
When the above code is executed, createTripledescryptoserviceproviderAfter the new instance is created, the key and IV are generated. CallGeneratekeyAndGenerateivThe method creates another key and IV.
Asymmetric Key
. NET Framework provides 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. You can store asymmetric keys for multiple sessions or generate asymmetric keys for only one session. The public key can be widely used, and the private key should be strictly protected.
A public/private key pair is generated every time a new instance of the asymmetric algorithm class is created. After creating a new instance of this type, you can use one of the following two methods to extract key information:
- Toxmlstring method, which returns the XML Representation of the key information.
- Exportparameters method, which returns rsaparameters enumeration to save key information.
Both methods accept a Boolean value indicating whether to return only public key information or both public and private key information. By using the importparameters method, you canRsacryptoserviceproviderClass initializationRsaparametersThe value of the structure.
The following code example createsRsacryptoserviceproviderClass, create a public/private key pair, and save the public key information inRsaparametersStructure.
[Visual Basic]'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 );
Store asymmetric keys in a key container
Do not store asymmetric private keys in plaintext on local computers. To store the private key, use the key container. For more information about key containers, see the CryptoAPI section in the Platform SDK documentation on the http://msdn.microsoft.com.
Create an asymmetric key and save it in the key container
- Create a new instance of the cspparameters class and pass the name you want the key container to the cspparameters. keycontainername field.
- A class derived from the asyuncricalgorithm class (usuallyRsacryptoserviceproviderOrDsacryptoserviceprovider) Create a new instance andCspparametersThe object is passed to its constructor.
Delete a key from a key container
- CreateCspparametersClass, and pass the name used by the key containerCspparameters. keycontainernameField.
- For slaveAsyuncricalgorithmA class derived from a class (usuallyRsacryptoserviceproviderOrDsacryptoserviceprovider) Create a new instance andCspparametersThe object is passed to its constructor.
- ToAsyuncricalgorithmThePersistkeyincspSet propertyFalse(In Visual BasicFalse).
- Call fromAsyuncricalgorihtmTheClearMethod. This method releases all resources of this class and clears the key container.
The following example illustrates the following process: Create an asymmetric key, save it in the key container, retrieve the key later, and delete the key from the container.
[Visual Basic] Imports systemimports system. ioimports system. security. cryptography_public class storekeypublic 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 cryptographicexceptionconsole. writeline (E. message) end tryend subpublic 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 subpublic 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 subpublic 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 accesss' the key iner. 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 subend 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 running the preceding example, the following content is displayed on 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.
You can use convert. tobase64string (TDES. Key) to convert the key into a string for storage.