Using RSA encryption and decryption algorithm in C #

Source: Internet
Author: User
Tags decrypt asymmetric encryption

first, what is RSA

RSA public Key cryptosystem. The so-called public key cryptosystem is to use different encryption keys and decryption keys, is a "cryptographic key derived from the known encryption key is not feasible in computing" cryptosystem.

In the public key cryptosystem, the encryption key (that is, the public key) PK is public information, and the decryption key (that is, secret key) SK is required to be confidential. Both the cryptographic algorithm E and the decryption algorithm d are also public. Although the key SK is determined by the public key PK, but can not calculate the SK based on PK. It is based on this theory that the famous RSA algorithm appeared in 1978, which is usually a pair of RSA keys, one of which is the secret key, which is saved by the user, the other is public key, can be exposed externally, even can be registered on the network server. To improve confidentiality, RSA keys are at least 500 bits long and 1024 bits are generally recommended. This makes the computation of encryption very large. In order to reduce the amount of computation, the traditional encryption method is used in conjunction with the public key encryption method when transmitting information, that is, the information is encrypted with an improved des or idea conversation key, and then the RSA key is used to encrypt the conversation key and the information digest. When the other party receives the message, it decrypts it with a different key and can check the information digest.

The RSA algorithm is the first algorithm that can be used for both encryption and digital signature, and it is easy to understand and manipulate. RSA is the most widely researched public-key algorithm , from the proposed to the present more than 30 years, experienced a variety of attacks, gradually accepted by people, widely regarded as one of the best public key scheme at present.

second, the choice of key length of RSA algorithm

1. The strength of the 1024x768 bit key in the asymmetric encryption algorithm is equivalent to the strength of the symmetric encryption algorithm 80bit key.

2. The key length increases by one time, the public key operation takes about 4 times times, the private key operation time increases about 8 times times, the public private key generation time approximately increases 16 times times.

3. Once encrypted cipher length is proportional to the length of the key, encrypted cipher length is the same as the key length (RSA encrypted content length is limited, and the key length, which is determined by its algorithm)

A, the encrypted plaintext length can not exceed the RSA key length minus 11byte, such as the key length is 1024 bits, 1024 bit =1024bit=128byte,128-11=117byte, so the plaintext length cannot exceed 117byte, If the length exceeds this value, an exception will be thrown.

b, the length of the cipher ciphertext is the length of the key, such as the key length of 1024bit (128Byte), the last generated ciphertext fixed to 1024bit (128Byte).

iii. RSA Plus decryption in C #

The. NET Framework Class Library provides the System.Security namespace, System. The security namespace provides the infrastructure of the common language runtime security system, including the base class for permissions, and the RSACryptoServiceProvider class is provided under the namespace to perform asymmetric encryption and decryption of the RSA algorithm.

1. Generation of key pairs:

A, directly generated according to RSACryptoServiceProvider

<summary>///generate key///</summary>public Rsakey Generatersakey () {    Rsakey rsakey = new Rsakey ();    RSACryptoServiceProvider RSA = new RSACryptoServiceProvider ();    Rsakey. Privatekey = RSA. Toxmlstring (true);    Generates the private key    Rsakey. PublicKey = RSA. Toxmlstring (false);    Generates the public key    RSA. Clear ();    return Rsakey;}

B. Generate a security certificate with the Makecert Certificate Creation Tool

Makecert-r-pe-n "Cn=rsakey"-B 03/31/2005-e 12/31/2012-sky Exchange-ss my

You can generate a certificate from the Visual Studio command prompt line by executing the above command.

To view the generated certificate:

Run-as Input MMC open console, select files, Add/Remove Snap-ins, find certificates on the left of the popup box, select Certificate Additions, select my user account, complete OK

At this point you can see the certificate we just created, named Rsakey, in the corresponding location, such as:

Finally, we can export the certificate as:

Where Rsakey.cer contains the public key for encryption, the RSAKEY.PFX contains the private key for decryption.

2. Create and decrypt RSA

<summary>///Create encryption rsa///</summary>///<param name= "PublicKey" > Public key </param>///<returns ></returns>private RSACryptoServiceProvider Createencryptrsa (string publickey) {try {RSACryptoServi        Ceprovider RSA = new RSACryptoServiceProvider (); Rsa.        Fromxmlstring (PublicKey);    return RSA;    } catch (Cryptographicexception ex) {throw ex; }}///<summary>///Create decryption rsa///</summary>///<param name= "Privatekey" > Private key </param>///< Returns></returns>private RSACryptoServiceProvider Createdecryptrsa (string privatekey) {try {RSACry        Ptoserviceprovider RSA = new RSACryptoServiceProvider (); Rsa.        Fromxmlstring (Privatekey);    return RSA;    } catch (Cryptographicexception ex) {throw ex; }}///<summary>///Create encryption rsa///</summary>///<param name= "CertFile" > Public key File </param>///based on security certificate <returns></returns>private RSACryptoServiceProviderX509certcreateencryptrsa (String certfile) {try {x509certificate2 X509cert = new X509Certificate2 (CertFile);        RSACryptoServiceProvider RSA = (RSACryptoServiceProvider) X509Cert.PublicKey.Key;    return RSA;    } catch (Cryptographicexception ex) {throw ex; }}///<summary>///rsa///</summary>///<param name= "keyfile" > Private key File </param>///< based on private key file creation param name= "password" > Access password with private key file </param>///<returns></returns>private RSACryptoServiceProvider X509certcreatedecryptrsa (String keyfile, string password) {try {x509certificate2 x5        09Cert = new X509Certificate2 (keyfile, password);        RSACryptoServiceProvider RSA = (RSACryptoServiceProvider) X509cert.privatekey;    return RSA;    } catch (Cryptographicexception ex) {throw ex; }}

The private key file and public key file mentioned therein are generated by the Makecert Certificate Creation tool, and the parameter password in the X509certcreatedecryptrsa method is the access password set by our export private key file. If you do not change your password, you cannot decrypt it even if you have a private key certificate.

3.RSA Plus decryption

<summary>///encryption///</summary>///<param name= "Datatoencrypt" > Data to be encrypted </param>///<param Name= "PublicKey" > Public key </param>///<returns></returns>public string Encrypt (String datatoencrypt,    String publickey) {Encoding encoder = Encoding.UTF8; byte[] _datatoencrypt = encoder.    GetBytes (Datatoencrypt); return this. Encrypt (_datatoencrypt, PublicKey);} <summary>///encryption///</summary>///<param name= "Datatoencrypt" > Data to be encrypted </param>///<param Name= "PublicKey" > Public key </param>///<returns></returns>public string Encrypt (byte[] Datatoencrypt, String publickey) {using (RSACryptoServiceProvider RSA = this. Createencryptrsa (PublicKey)) {byte[] EncryptedData = RSA.        Encrypt (Datatoencrypt, false); return this.    Bytestohexstring (EncryptedData); }}///<summary>///According to security certificate///</summary>///<param name= "Datatoencrypt" ></param>///< param name= "CertFile" ></param><returns></returns>public string X509certencrypt (String datatoencrypt, String certfile) {Encoding Enco    Der = Encoding.UTF8; byte[] _datatoencrypt = encoder.    GetBytes (Datatoencrypt); return this. X509certencrypt (_datatoencrypt, CertFile);} <summary>///encryption//</summary>///<param name= "Datatoencrypt" > Data to be encrypted </param>///< param name= "CertFile" > Security certificate </param>///<returns></returns>public string X509certencrypt (byte[] Datatoencrypt, String certfile) {if (!    File.exists (CertFile)) {throw new ArgumentNullException (CertFile, "Encryption certificate not Found"); } using (RSACryptoServiceProvider RSA = this. X509certcreateencryptrsa (CertFile)) {byte[] EncryptedData = RSA.        Encrypt (Datatoencrypt, false); return this.    Bytestohexstring (EncryptedData); }}///<summary>///decryption//</summary>///<param name= "EncryptedData" > Data to be decrypted </param>///< param name= "Privatekey" > Private key </param>///<retuRns></returns>public string Decrypt (String EncryptedData, String privatekey) {using ( RSACryptoServiceProvider RSA = this.        Createdecryptrsa (Privatekey)) {Encoding encoder = Encoding.UTF8;        byte[] _encrypteddata = hexstringtobytes (EncryptedData); byte[] Decrypteddata = RSA.        Decrypt (_encrypteddata, false); Return encoder.    GetString (Decrypteddata); }}///<summary>///decryption//</summary>///<param name= "EncryptedData" > Data to be decrypted </param>///< param name= "keyfile" > Private key file </param>///<param name= "password" > Access private key file password </param>///<returns ></returns>public string X509certdecrypt (String EncryptedData, String keyfile, string password) {if (!    File.exists (keyfile)) {throw new ArgumentNullException (KeyFile, "Decryption certificate not Found"); } using (RSACryptoServiceProvider RSA = this.        X509certcreatedecryptrsa (keyfile, password)) {Encoding encoder = Encoding.UTF8; byte[] _encrypteddata = HexstringtobYtes (EncryptedData); byte[] Decrypteddata = RSA.        Decrypt (_encrypteddata, false); Return encoder.    GetString (Decrypteddata); }}

Finally, a simple demo is compiled:

Demo Download: Rsacrypto.rar

Resources:

http://dustin.iteye.com/blog/763931

Http://baike.baidu.com/view/539299.htm

Http://www.cnblogs.com/yjmyzz/archive/2008/08/20/1272098.html

Using RSA encryption and decryption algorithm in C #

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.