Key storage of asymmetric encryption algorithms in. net

Source: Internet
Author: User
Tags asymmetric encryption

Key storage of asymmetric encryption algorithms in. net

In. net, the RSA algorithm is used for data encryption and signature. 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 (boolincludeprivateparameters) 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:

 

        static void SaveKey2File(RSACryptoServiceProvider rsa, string fileName)        {            FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);            string key = rsa.ToXmlString(false);            fs.Write(Encoding.UTF8.GetBytes(key), 0, key.Length);            fs.Close();            fs.Dispose();        }         static void LoadKeyFromFile(RSACryptoServiceProvider rsa, string fileName)         {             FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);             byte[] data = new byte[fs.Length];             fs.Read(data, 0, (int)fs.Length);             fs.Close();             fs.Dispose();             rsa.FromXmlString(Encoding.UTF8.GetString(data));         }

 

ActualWorkFor security reasons, the above method is rarely used to save the key. 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 to store keys (userkey store and machine key store). The key container is a unit used to store keys, 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:

Static void createcontainer (rsacryptoserviceprovider RSA, string filename) {// instantiate the cspparameters object cspparameters csppara = new cspparameters (); // specify the cspparameters object instance name csppara. keycontainername = "key_container_test"; // set the key type to exchange csppara. keynumber = 1; // set the key container to save it to the computer keystore (default: User keystore) csppara. flags = cspproviderflags. usemachinekeystore; // when instantiating an RSA object, pass the cspparameters object as a constructor parameter to the RSA object. // if the key container named key_container_test does not exist, the RSA object will create this key container; // if the key container named key_container_test already exists, the RSA object will use the key in this key container to instantiate rsacryptoserviceprovider rsapro = new rsacryptoserviceprovider (csppara );}

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

Static void deletecontainer (rsacryptoserviceprovider RSA, string filename) {cspparameters csppara = new cspparameters (); csppara. keycontainername = "key_container_test"; csppara. flags = cspproviderflags. usemachinekeystore; rsacryptoserviceprovider rsapro = new rsacryptoserviceprovider (csppara); // This key container rsapro is not saved in the keystore. persistkeyincsp = false; // release all resources occupied by rsapro, including the key container. 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.

Certificate

One copyCertificateIt contains a public key and information related to the certificate publisher. It is used to ensure that the public key is generated by the publisher mentioned in the certificate. A certificate is a statement that contains the digital signature generated by the private key owner. The private key owner first obtains the trust of the Certification Authority (CA), and then the validators are responsible for ensuring the validity of the public key. This technology can create a trust relationship between two unknown entities. The certificate also includes the certificate validity period and other information.

There are many organizations (CAS) that provide verification services on the Internet, and VeriSign is popular. On the Intranet, you can use the Certificate Service in Windows Server to run your certificate authority (CA) service.

X.509

X.509 is a common certificate standard. For example, Windows Authenticode and SSL both use X.509 Certificate standards.

The. NET Framework SDK provides the makecert tool used to generate a test certificate.

Run the following command:Mskecert-N Cn = test. CER generates a certificate named test. Cer. For a formal digital certificate, you must go to the CA to apply for it. Of course, you must pay for it.

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:

Static byte [] encryptdatabycert (byte [] data) {// instantiate an x509certificate2 object and load the certificate testcertificate. CER x509certificate2 Cert = new x509certificate2 (@ "C: \ testcertificate. CER "); // convert the public key of the certificate into an rsacryptoserviceprovider object. Then, you can use this object to perform the encryption operation rsacryptoserviceprovider RSA = (rsacryptoserviceprovider) cert. publickey. key; byte [] endata = RSA. encrypt (data, false); Return endata ;}

 

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:

Static string decryptbycert (byte [] endata) {// instantiate an x509certificate2 object and load the certificate testcertificate. pfx. // Because of the certificate testcertificate. pfx contains the private key. Therefore, you must provide the private key protection password (the second parameter). x509certificate2 Cert = new x509certificate2 (@ "C: \ testcertificate. pfx "," 123456 "); // certificate testcertificate. the private key of pfx is forcibly converted to an rsacryptoserviceprovider object, which is used to decrypt rsacryptoserviceprovider RSA = (rsacryptoserviceprovider) cert. privatekey; byte [] DATA = RSA. decrypt (endata, false); return data ;}

 

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
Http://technet.microsoft.com/zh-cn/library/cc784662%28WS.10%29.aspx>. The specific code for accessing the certificate storage area is as follows:

Private x509certificate2 getcertificate (string certname) {// declare the x509store object, specify the name of the bucket and the type of the bucket. // storename defines the logical name of some default buckets. x509store = new x509store (storename. my, storelocation. currentuser); // open the bucket in read-only mode, and store in the open mode defined by openflags. open (openflags. readonly); // obtain the set of digital certificates in this bucket x509certificate2collection certcol = store. certificates; // find the certificate that meets the Certificate Name and return foreach (x509certificate2 cert in certcol) {If (cert. subjectname. name = "cn =" + certname) {store. close (); Return Cert;} store. close (); return NULL ;}

 

You can also use the x509certificate2collection object to add or delete a certificate in the current bucket.

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.

 

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.