Implementation of RSA encryption and decryption and signature and verification in C #

Source: Internet
Author: User
Tags asymmetric encryption

Reprinted from: http://blog.csdn.net/llwinnner/archive/2009/03/21/4011936.aspx

 

RSA is an asymmetric encryption algorithm. RSA is widely used in public key encryption standards and electronic commerce. RSA was proposed in 1977 by Ronald Rivest, Adi Shamir, and Leonard Adleman. Both of them were working at the Massachusetts Institute of Technology. RSA is a combination of the first letters of the three of them .. Net, we can use the encryption service provided by classes in. Net Framework to ensure data security. Currently, RSA is widely used for encryption. In. Net Framework, there are two main classes related to RSA encryption algorithms: RSA class and RSACryptoServiceProvider class. According to MSDN, the RSA class "represents the base class inherited from all the implementations of the RSA algorithm", and the RSACryptoServiceProvider class is "using the encryption service provider (CSP) the provided RSA algorithm implements asymmetric encryption and decryption ". In addition, the RSAParameters structure of "representing standard parameters of the RSA algorithm" is also very important. It stores the parameters of the RSA algorithm.
The following describes how to use the RSA algorithm provided by the Framework to encrypt, sign, verify, and decrypt our information in C #.

  

Using System. security. cryptography; using System. management; using Microsoft. win32; /// <summary> /// generate a public/private key /// </summary> /// <param name = "PrivateKeyPath"> </param> /// <param name = "PublicKeyPath"> </param> public void RSAKey (string PrivateKeyPath, string PublicKeyPath) {try {RSACryptoServiceProvider provider = new RSACryptoServiceProvider (); this. createPrivateKeyXML (PrivateKeyPath, provider. toXmlString (true); this. createPublicKeyXML (PublicKeyPath, provider. toXmlString (false);} catch (Exception exception) {throw exception ;}} /// <summary> /// perform MD5 encryption on the original data /// </summary> /// <param name = "m_strSource"> data to be encrypted </param> /// <returns> returns confidential data </returns> public string GetHash (string m_strSource) {HashAlgorithm algorithm = HashAlgorithm. create ("MD5"); byte [] bytes = Encoding. getEncoding ("GB2312 "). getBytes (m_strSource); byte [] inArray = algorithm. computeHash (bytes); return Convert. toBase64String (inArray );} /// <summary> // RSA encryption /// </summary> /// <param name = "xmlPublicKey"> Public Key </param> /// <param name = "m_strEncryptString"> MD5 encrypted data </param> // <returns> RSA public key encrypted data </returns> public string RSAEncrypt (string xmlPublicKey, string m_strEncryptString) {string str2; try {RSACryptoServiceProvider provider = new RSACryptoServiceProvider (); provider. fromXmlString (xmlPublicKey); byte [] bytes = new UnicodeEncoding (). getBytes (m_strEncryptString); str2 = Convert. toBase64String (provider. encrypt (bytes, false);} catch (Exception exception) {throw exception;} return str2 ;} /// <summary> // RSA decryption /// </summary> /// <param name = "xmlPrivateKey"> Private Key </param> /// <param name = "m_strDecryptString"> data to be decrypted </param> // <returns> decrypted result </returns> public string RSADecrypt (string xmlPrivateKey, string m_strDecryptString) {string str2; try {RSACryptoServiceProvider provider = new RSACryptoServiceProvider (); provider. fromXmlString (xmlPrivateKey); byte [] rgb = Convert. fromBase64String (m_strDecryptString); byte [] buffer2 = provider. decrypt (rgb, false); str2 = new UnicodeEncoding (). getString (buffer2);} catch (Exception exception) {throw exception;} return str2 ;} /// <summary> /// sign the ciphertext after MD5 encryption /// </summary> /// <param name = "p_strKeyPrivate"> Private Key </param >/// <param name = "m_strHashbyteSignature"> MD5 encrypted ciphertext </param> /// <returns> </returns> public string SignatureFormatter (string p_strKeyPrivate, string m_strHashbyteSignature) {byte [] rgbHash = Convert. fromBase64String (m_strHashbyteSignature); RSACryptoServiceProvider key = new RSACryptoServiceProvider (); key. fromXmlString (p_strKeyPrivate); RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter (key); formatter. setHashAlgorithm ("MD5"); byte [] inArray = formatter. createSignature (rgbHash); return Convert. toBase64String (inArray );} /// <summary> /// signature verification /// </summary> /// <param name = "p_strKeyPublic"> Public Key </param> /// <param name = "p_strHashbyteDeformatter"> User name to be verified </param> // <param name = "p_strDeformatterData"> Registration Code </param> /// <returns> </returns> public bool SignatureDeformatter (string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData) {try {byte [] rgbHash = Convert. fromBase64String (p_strHashbyteDeformatter); RSACryptoServiceProvider key = new RSACryptoServiceProvider (); key. fromXmlString (p_strKeyPublic); RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter (key); deformatter. setHashAlgorithm ("MD5"); byte [] rgbSignature = Convert. fromBase64String (p_strDeformatterData); if (deformatter. verifySignature (rgbHash, rgbSignature) {return true;} return false;} catch {return false ;}} /// <summary> /// obtain the hard disk ID /// </summary> /// <returns> hard disk ID </returns> public string GetHardID () {string HDInfo = ""; ManagementClass cimobject1 = new ManagementClass ("Win32_DiskDrive"); ManagementObjectCollection moc1 = callback (); foreach (ManagementObject mo in moc1) {HDInfo = (string) mo. properties ["Model"]. value;} return HDInfo ;} /// <summary> /// read the key value specified in the Registry /// </summary> /// <param name = "key"> key name </param> /// <returns> return key value </returns> private string ReadReg (string key) {string temp = ""; try {RegistryKey myKey = Registry. localMachine; RegistryKey subKey = myKey. openSubKey (@ "SOFTWARE \ JX \ Register"); temp = subKey. getValue (key ). toString (); subKey. close (); myKey. close (); return temp;} catch (Exception) {throw; // This registration item may not exist ;}} /// <summary> /// create the key and value specified in the Registry /// </summary> /// <param name = "key"> key name </param> /// <param name = "value"> key value </param> private void WriteReg (string key, string value) {try {RegistryKey rootKey = Registry. localMachine. createSubKey (@ "SOFTWARE \ JX \ Register"); rootKey. setValue (key, value); rootKey. close () ;}catch (Exception) {throw ;}} /// <summary> /// create a public key file /// </summary> /// <param name = "path"> </param> /// <param name = "publickey"> </param> public void CreatePublicKeyXML (string path, string publickey) {try {FileStream publickeyxml = new FileStream (path, FileMode. create); StreamWriter sw = new StreamWriter (publickeyxml); sw. writeLine (publickey); sw. close (); publickeyxml. close () ;}catch {throw ;}} /// <summary> /// create the private key file /// </summary> /// <param name = "path"> </param> /// <param name = "privatekey"> </param> public void CreatePrivateKeyXML (string path, string privatekey) {try {FileStream privatekeyxml = new FileStream (path, FileMode. create); StreamWriter sw = new StreamWriter (privatekeyxml); sw. writeLine (privatekey); sw. close (); privatekeyxml. close () ;}catch {throw ;}} /// <summary> /// read the Public Key // </summary> /// <param name = "path"> </param> /// <returns> </returns> public string ReadPublicKey (string path) {StreamReader reader = new StreamReader (path); string publickey = reader. readToEnd (); reader. close (); return publickey ;} /// <summary> /// read the private key /// </summary> /// <param name = "path"> </param> /// <returns> </returns> public string ReadPrivateKey (string path) {StreamReader reader = new StreamReader (path); string privatekey = reader. readToEnd (); reader. close (); return privatekey;} // <summary> // initializes the Registry and is called when the program is running, update the public Key xml // </summary> // <param name = "path"> public Key path </param> public void InitialReg (string path) {Registry. localMachine. createSubKey (@ "SOFTWARE \ JX \ Register"); Random ra = new Random (); string publickey = this. readPublicKey (path); if (Registry. localMachine. openSubKey (@ "SOFTWARE \ JX \ Register "). valueCount <= 0) {this. writeReg ("RegisterRandom", ra. next (1,100000 ). toString (); this. writeReg ("RegisterPublicKey", publickey);} else {this. writeReg ("RegisterPublicKey", publickey );}}

If you want to encrypt and decrypt the sent message, use the public key for encryption and the private key for decryption. The ciphertext cannot be cracked even if it is stolen.

If you want to register the software and generate a registration code, the server uses the private key to encrypt the user's hard disk number, and the client uses the public key to decrypt it. After decryption, the client's hard disk number is encrypted by MD5, compare the obtained results with the decrypted results. If the results are the same, they indicate that they are registered users. Otherwise, they are non-registered users.

 

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/llwinnner/archive/2009/03/21/4011936.aspx

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.