Saving the key of the asymmetric encryption RSA Algorithm in. net

Source: Internet
Author: User

 

 

We have discussed how to use the RSA algorithm to encrypt and sign data in. net. In many cases, we need to reuse a set of keys, so we need to save these keys. Next, I will introduce three methods for saving keys in. net.

Method 1: Export and save the key as a local file.

We recommend that you do not use this method to save the private key for security reasons. If you use this method, only the public key is exported during key export.

The rsacryptoserviceprovider object provides a toxmlstring (bool includeprivateparameters) method. We can use this method to export the key to a string in XML format and save it to a file, if this method is set to true, the private key is exported. Otherwise, the private key is not exported. When necessary, we can use the fromxmlstring (string xmlstring) method to load the stored key information to the rsacryptoserviceprovider object. The following code exports and imports data:

   1: static void SaveKey2File(RSACryptoServiceProvider rsa, string fileName)

   2: {

   3:     FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);

   4:     string key = rsa.ToXmlString(false);

   5:     fs.Write(Encoding.UTF8.GetBytes(key), 0, key.Length);

   6:     fs.Close();

   7:     fs.Dispose();

   8: }

   9:  

  10: static void LoadKeyFromFile(RSACryptoServiceProvider rsa, string fileName)

  11: {

  12:     FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

  13:     byte[] data = new byte[fs.Length];

  14:     fs.Read(data, 0, (int)fs.Length);

  15:     fs.Close();

  16:     fs.Dispose();

  17:     rsa.FromXmlString(Encoding.UTF8.GetString(data));

  18: }

In practice, the above method is rarely used to save the key for security reasons. However, if you want to see what the key looks like, this method is quite useful ~~

Method 2: Save the key to the key container.

What is a key container? The window system provides two key stores for saving the user key store and machine key store, and the key container is a unit used to save the key, each key container contains a set of key pairs (public and private keys) and other information, such as whether to allow the export of keys, types of keys (exchange or signatrue), etc, you can access them by using the secret container name.

Use the cspparameters object to create or use a key container:

1: // instantiate the cspparameters object

   2: CspParameters cspPara = new CspParameters();

3: // specify the name of the cspparameters object instance

   4: cspPara.KeyContainerName = "key_container_test";

5: // set the key type to exchange

   6: cspPara.KeyNumber = 1;

7: // set the key container to save it to the computer keystore (the default is the user keystore)

   8: cspPara.Flags = CspProviderFlags.UseMachineKeyStore;

9: // when instantiating an RSA object, pass the cspparameters object as a constructor parameter to the RSA object,

10: // if the key container named key_container_test does not exist, the RSA object will create this key container;

11: // if the key container named key_container_test already exists, the RSA object will use the key in the key container for instantiation.

  12: RSACryptoServiceProvider rsaPro = new RSACryptoServiceProvider(cspPara);

  13:  

 

Delete key container: when you no longer need a key container, you can use the following method to delete it.

   1: CspParameters cspPara = new CspParameters();

   2: cspPara.KeyContainerName = "key_container_test";

   3: cspPara.Flags = CspProviderFlags.UseMachineKeyStore;

   4: RSACryptoServiceProvider rsaPro = new RSACryptoServiceProvider(cspPara);

5: // This key container is not saved in the keystore

   6: rsaPro.PersistKeyInCsp = false;

7: // release all resources occupied by rsapro, including the key container.

   8: rsaPro.Clear();

The key container cannot be extracted from the keystore unless you know the name of the key container, so the key (especially the private key) used on the local machine) it is safer to save it in a key container.

Note: When we instantiate an rsacryptoserviceprovider object, the rsacryptoserviceprovider object will generate a temporary key container if no specific cspparameters object is specified, the temporary key container is automatically deleted when the rsacryptoserviceprovider object is destroyed.

Method 3: Use a digital certificate.

 

 

 

If your key needs to be used on different machines, it is a good choice to save the key in the digital certificate. In fact, it is not accurate to save the key in the digital certificate. It should be a digital certificate, and then use the key in the digital certificate.

How to generate a digital certificate? For a formal digital certificate, you must go to the CA to apply for it. Of course, you must pay for it. Fortunately, we can use makecert.exe of. Net sdk.pdf to generate a temporary digital certificate. For details about how to generate a certificate, visit the certificate creation tool.

The object used to access the Certificate in. NET is x509certificate2. We can use it to load a digital certificate and obtain the key in the digital certificate.

If the certificate is saved locally as a file, load it using the following method:

   1: static byte[] EncryptDataByCert(byte[] data)

   2: { 

3: // instantiate an x509certificate2 object and load the certificate testcertificate. Cer.

   4:     X509Certificate2 cert = new X509Certificate2(@"c:\testCertificate.cer");

5: // forcibly convert the public key of the certificate into an rsacryptoserviceprovider object. Then, you can use this object to perform encryption operations.

   6:     RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PublicKey.Key;

   7:     byte[] enData = rsa.Encrypt(data, false);

   8:     return enData;

   9: }

Generally, for a digital certificate, the certificate that saves the public key is used. CER extension, and the certificate that saves the private key will use. pfx extension. When we load a digital certificate with a private key, we need to provide a password to protect the private key. The Code is as follows:

   1: static string DecryptByCert(byte[] endata)

   2: {

3: // instantiate an x509certificate2 object and load the certificate testcertificate. pfx.

4: // because the certificate testcertificate. pfx contains the private key, you need to provide the private key protection password (the second parameter)

   5:     X509Certificate2 cert = new X509Certificate2(@"c:\testCertificate.pfx", "123456");

6: // convert the private key of the certificate testcertificate. pfx to an rsacryptoserviceprovider object for decryption.

   7:     RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;

   8:     byte[] data = rsa.Decrypt(endata, false);

   9:     return data;

  10: }

If the certificate is stored in the certificate store on the computer, we need to use another object x509store to access the certificate store. According to the access permission, the certificate storage is divided into two parts: the current user and the local machine. The former is used to save the digital certificate that the current user can use, the latter is used to save the digital certificates that can be used to log on to the local machine. Both the current user and the Local Computer contain multiple logical storage zones, which are differentiated by different names. Each logical storage zone can store multiple digital certificates. For more details, refer to certificates. The specific code for accessing the certificate storage area is as follows:

   1: private X509Certificate2 GetCertificate(string CertName)

   2: {

3: // declare the x509store object, specifying the name and type of the bucket

4: // storename defines the logical names of some default storage areas.

   5:     X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);

6: // open the bucket in read-only mode, which is defined by openflags.

   7:     store.Open(OpenFlags.ReadOnly);

8: // obtain the set of digital certificates in the bucket

   9:     X509Certificate2Collection certCol = store.Certificates;

10: // find the certificate that meets the Certificate Name and return

  11:     foreach (X509Certificate2 cert in certCol)

  12:     {

  13:         if (cert.SubjectName.Name == "CN="  + CertName)

  14:         {

  15:             store.Close();

  16:             return cert;

  17:         }

  18:     }

  19:     store.Close();

  20:     return null;

  21: }

You can also use the x509certificate2collection object to add and delete certificates in the current storage area. For more information, see certificate storage area.

The above is my own understanding of key storage. You can select a specific method based on your actual situation. I hope it will be helpful to you. If any great God has a better way, we hope to keep your methods for us to learn.

 

 

 

 

Technorati tags: RSA, C #,. net, digital certificate, asymmetric encryption

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.