C # example of encryption and decryption using RSA certificate files

Source: Internet
Author: User

Modify the example on MSDN so that it can be encrypted and decrypted through the RSA Certificate file. A small problem occurs in the middle.

Q: When the ExportParameters () method is executed, return CryptographicException: This item is not suitable for use in the specified state (Key not valid for use in specified state ).

A: When importing A certificate with A private key, you need to use"X509KeyStorageFlags"Parameter mark" private key can be exported ".

X509Certificate2 prvcrt = new X509Certificate2 (@ "X: \ path \ to \ CA. pfx", "*** password ***", X509KeyStorageFlags. Exportable);

The following is an example program:

View Code

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 UnicodeEncoder 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())                //{                    //Console.WriteLine(RSA.ToXmlString(false));                    //Pass the data to ENCRYPT, 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, bool DoOAEPPadding)        {            try            {                byte[] encryptedData;                //Create a new instance of RSACryptoServiceProvider.                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())                {                    //Import the RSA Key information. This 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);                }                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 only 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;            }        }    }}

 

 

 

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.