C # using RSA certificate file encryption and decryption examples

Source: Internet
Author: User
Tags decrypt

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:

Using system;using system.collections.generic;using system.linq;using system.text;namespace TeatApp_Crypto{using    System;    Using System.Security.Cryptography;    Using System.Security.Cryptography.X509Certificates;    Using System.Text; Class Rsacspsample {static void Main () {try {//create a Unicodeen                Coder to convert between byte array and string.                UnicodeEncoding byteconverter = new UnicodeEncoding ();                Create byte arrays to hold original, encrypted, and decrypted data.                byte[] Datatoencrypt = Byteconverter.getbytes ("Data to Encrypt");                Byte[] EncryptedData;                Byte[] Decrypteddata;                X509Certificate2 pubcrt = new X509Certificate2 (@ "X:\PATH\TO\CA.CRT"); RSACryptoServiceProvider PubKey = (RSACryptoServiceProvider) pubcrt.                Publickey.key; X509Certificate2 prvcrt = new X509Certificate2 (@ "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 ())//{//consol E.writeline (RSA.                    Toxmlstring (false)); Pass the data to ENCRYPT, the public key information//(using Rsacryptoserviceprovider.exportparamet                    ERs (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.exportparame TERS (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, bool dooaeppadding)                {try {byte[] EncryptedData;                Create a new instance of RSACryptoServiceProvider. using (RSacryptoserviceprovider RSA = new RSACryptoServiceProvider ()) {//import The RSA Key inf Ormation.                    This is needs//toinclude the public key information. Rsa.                    ImportParameters (Rsakeyinfo);                      Encrypt the passed byte array and specify OAEP padding.                      OAEP padding is a available on Microsoft Windows XP or//later. EncryptedData = RSA.                Encrypt (Datatoencrypt, dooaeppadding);            } return EncryptedData;            }//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, bool dooaeppadding) {try {byte[] deCrypteddata;                Create a new instance of RSACryptoServiceProvider.  using (rsacryptoserviceprovider RSA = new RSACryptoServiceProvider ()) {//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 a available on Microsoft Windows XP or//later. Decrypteddata = RSA.                Decrypt (dataToDecrypt, dooaeppadding);            } return decrypteddata;            }//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.