C # using RSA certificate file encryption and decryption examples

Source: Internet
Author: User
Tags decrypt

Original: C # using RSA certificate file encryption and decryption example

Modify the example on MSDN so that it can be encrypted and decrypted through the RSA certificate file, and encounter a minor problem in the middle.

Q: When executing the Exportparameters () method, the return Cryptographicexception: The item is not suitable to be used in a specified state (key is not valid for using in specified).

A: When you import a certificate with a private key, you need to mark "private key exportable" with the "x509keystorageflags" parameter.

x509certificate2 prvcrt = new x509certificate2 (@ "X:\path\to\CA.pfx", "*** password*** " , x509keystorageflags.exportable);

The following is an example program:

View Code
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceteatapp_crypto{usingSystem; usingSystem.Security.Cryptography; usingSystem.Security.Cryptography.X509Certificates; usingSystem.Text; classRsacspsample {Static voidMain () {Try            {                //Create a unicodeencoder to convert between byte array and string.UnicodeEncoding Byteconverter =Newunicodeencoding (); //Create byte arrays to hold original, encrypted, and decrypted data.                byte[] Datatoencrypt = Byteconverter.getbytes ("Data to Encrypt"); byte[] EncryptedData; byte[] decrypteddata; X509Certificate2 PUBCRT=NewX509Certificate2 (@"X:\PATH\TO\CA.CRT"); RSACryptoServiceProvider PubKey=(RSACryptoServiceProvider) pubcrt.                Publickey.key; X509Certificate2 PRVCRT=NewX509Certificate2 (@"X:\path\to\CA.pfx","***password***", x509keystorageflags.exportable); RSACryptoServiceProvider Prvkey=(RSACryptoServiceProvider) prvcrt.                Privatekey; //Create A new instance of RSACryptoServiceProvider to generate//Public and private key data. //using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider ())//{                    //Console.WriteLine (RSA.                    Toxmlstring (false)); //Pass The data to ENCRYPT, and the public key information//(using Rsacryptoserviceprovider.exportparameters (false),//And A Boolean flag specifying no OAEP padding.EncryptedData = Rsaencrypt (Datatoencrypt, PubKey. Exportparameters (false),false); Console.WriteLine ("Encrypted plaintext: {0}", Convert.tobase64string (EncryptedData)); //Pass The data to DECRYPT, the private key information//(using Rsacryptoserviceprovider.exportparameters (true),//And A Boolean flag specifying no OAEP padding.Decrypteddata = Rsadecrypt (EncryptedData, Prvkey. Exportparameters (true),false); //Display The decrypted plaintext to the console.Console.WriteLine ("decrypted plaintext: {0}", Byteconverter.getstring (Decrypteddata)); //}Prvkey.                Clear (); PubKey.                Clear ();            Console.read (); }            Catch(ArgumentNullException) {//Catch This exception in case the encryption did//Not succeed.Console.WriteLine ("encryption failed."); }        }        Static  Public byte[] Rsaencrypt (byte[] Datatoencrypt, RSAParameters Rsakeyinfo,BOOLdooaeppadding) {            Try            {                byte[] EncryptedData; //Create A new instance of RSACryptoServiceProvider.                using(RSACryptoServiceProvider RSA =NewRSACryptoServiceProvider ()) {                    //Import the RSA Key information. this is only needs//toinclude the public key information.RSA.                    ImportParameters (Rsakeyinfo); //Encrypt the passed byte array and specify OAEP padding. //OAEP padding is only available on Microsoft Windows XP or//later. EncryptedData =RSA.                Encrypt (Datatoencrypt, dooaeppadding); }                returnEncryptedData; }            //Catch and display a cryptographicexception//to the console.            Catch(Cryptographicexception e) {Console.WriteLine (e.message); return NULL; }        }        Static  Public byte[] Rsadecrypt (byte[] dataToDecrypt, RSAParameters Rsakeyinfo,BOOLdooaeppadding) {            Try            {                byte[] decrypteddata; //Create A new instance of RSACryptoServiceProvider.                using(RSACryptoServiceProvider RSA =NewRSACryptoServiceProvider ()) {                    //Import the RSA Key information. This needs//To include the private key information.RSA.                    ImportParameters (Rsakeyinfo); //Decrypt the passed byte array and specify OAEP padding. //OAEP padding is only available on Microsoft Windows XP or//later. Decrypteddata =RSA.                Decrypt (dataToDecrypt, dooaeppadding); }                returnDecrypteddata; }            //Catch and display a cryptographicexception//to the console.            Catch(Cryptographicexception e) {Console.WriteLine (e.tostring ()); return NULL; }        }    }}

C # using RSA certificate file encryption and decryption examples

Related Article

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.