关于RSA加密
RSA算法是一种非对称密码算法,所谓非对称,就是指该算法需要一对密钥,使用其中一个加密,则需要用另一个才能解密。
RSA的算法涉及三个参数,n、e1、e2。
其中,n是两个大质数p、q的积,n的二进制表示时所占用的位数,就是所谓的密钥长度。
e1和e2是一对相关的值,e1可以任意取,但要求e1与(p-1)*(q-1)互质;再选择e2,要求(e2*e1)mod((p-1)*(q-1))=1。
(n及e1),(n及e2)就是密钥对。
RSA加解密的算法完全相同,设A为明文,B为密文,则:A=B^e1 mod n;B=A^e2 mod n;
e1和e2可以互换使用,即:
A=B^e2 mod n;B=A^e1 mod n;
using System.Security.Cryptography;
/// <summary> /// RSA加密 /// </summary> /// <param name="publickey"></param> /// <param name="content"></param> /// <returns></returns> public static string RSAEncrypt(string publickey, string content) { publickey = @"<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(publickey); cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false); return Convert.ToBase64String(cipherbytes); } /// <summary> /// RSA解密 /// </summary> /// <param name="privatekey"></param> /// <param name="content"></param> /// <returns></returns> public static string RSADecrypt(string privatekey, string content) { privatekey = @"<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent><P>/hf2dnK7rNfl3lbqghWcpFdu778hUpIEBixCDL5WiBtpkZdpSw90aERmHJYaW2RGvGRi6zSftLh00KHsPcNUMw==</P><Q>6Cn/jOLrPapDTEp1Fkq+uz++1Do0eeX7HYqi9rY29CqShzCeI7LEYOoSwYuAJ3xA/DuCdQENPSoJ9KFbO4Wsow==</Q><DP>ga1rHIJro8e/yhxjrKYo/nqc5ICQGhrpMNlPkD9n3CjZVPOISkWF7FzUHEzDANeJfkZhcZa21z24aG3rKo5Qnw==</DP><DQ>MNGsCB8rYlMsRZ2ek2pyQwO7h/sZT8y5ilO9wu08Dwnot/7UMiOEQfDWstY3w5XQQHnvC9WFyCfP4h4QBissyw==</DQ><InverseQ>EG02S7SADhH1EVT9DD0Z62Y0uY7gIYvxX/uq+IzKSCwB8M2G7Qv9xgZQaQlLpCaeKbux3Y59hHM+KpamGL19Kg==</InverseQ><D>vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=</D></RSAKeyValue>"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(privatekey); cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false); return Encoding.UTF8.GetString(cipherbytes); }
原文来自:
http://www.cnblogs.com/linzheng/archive/2011/02/20/1959123.html
公钥和密钥的生成:
private void but() { //使用默认密钥创建RSACryptoServiceProvider对象 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); //显示包含公钥/私钥对的XML表示形式,如果只显示公钥,将参数改为false即可 Write_Txt(rsa.ToXmlString(false)); //这生成了公钥和密钥 //将被加密的字符串转换为字节数组 byte[] dataToEncrypt = Encoding.UTF8.GetBytes("hello"); try { //得到加密后的字节数组 byte[] encryptedData = rsa.Encrypt(dataToEncrypt, false); this.richTextBox1.AppendText(Encoding.UTF8.GetString(encryptedData)+" \n"); //得到解密后的字节数组 rsaDecrypt(encryptedData); byte[] decryptedData = rsa.Decrypt(encryptedData, false); this.richTextBox1.AppendText("解密"+Encoding.UTF8.GetString(decryptedData) + " \n"); } catch (Exception err) { MessageBox.Show(err.Message); } }
封装了一下,写到一个类中。加密后的内容写到文件里。解密的时候读取:
public class RSCEN { /* * <RSAKeyValue><Modulus>ql+LrSBSyTeRQJN24dR76iRoNi8kRs7wYlwG0FRLuujGkR62HJTD/YM/7miAxCR0lufVGx6E0Ej46OSwIRsqwQo/C2WUnvjlbs/bGiiXkD7IC9lsmzQQEvVjTyrUMVzs7NQMoXwzvIiGGPUzPrPfuXOuPDtbOD/odr3e4pOP6ts=</Modulus><Exponent>AQAB</Exponent><P>3wM9IzYsOEa3eruVG0qjZ5IL4YleDVsCcTma9LT5cQitx4vAKUhYPuljH7ILl669cEWjmt/xGLw6uuOxD3VpYQ==</P><Q>w5MGBeFi3roc+SszgOJpl3QxinxIhcXsCXA/aXYXOtTMqcXCGuV3atSS+YDaP5zt0Nrvedrr6hHaoLfzMZyRuw==</Q><DP>E9eO7f4Y6xznoETmXFpEtadZ5UQ6mQea7QYKEnGzq+nwxEtb2pB0QYy0ZBKMU3+ZnU6k4te/9Mpyk0RE8bIpoQ==</DP><DQ>T4sZtQSRcOMja5hNj0sHBUmF6LxZxsbUFJapw9v64LuyLg63vra7liC1UnM80QijlQGmytnmf8IZOKr4Z6I1hw==</DQ><InverseQ>yfjwKeVxrr8Docp69gaEkoFFY1IwTw+Jpkf/LXIW+s5IZeqbhT7VoO5AXXMvhEGLi1IreNmzqEbhNVw3CudV6Q==</InverseQ><D>SfvBoMV3ja9WoQ8oQbrOsIdsxZLFEwaL9np17wOb+ydYCu6mMFUdornbCkFRIVufUWSM8wDWtcfqZt/f6BBvCL0P2xwBRuNWLP2fY8Yw/puyIlz5p2M3VcUBQcoZ63tX9NkQ3uaqFAlOKW0VrYDjviKPx5NhcR1glkdgYfDahUE=</D></RSAKeyValue> * */ #region 钥匙 /// <summary> /// 公钥 /// </summary> private static string publickey = @"<RSAKeyValue><Modulus>ql+LrSBSyTeRQJN24dR76iRoNi8kRs7wYlwG0FRLuujGkR62HJTD/YM/7miAxCR0lufVGx6E0Ej46OSwIRsqwQo/C2WUnvjlbs/bGiiXkD7IC9lsmzQQEvVjTyrUMVzs7NQMoXwzvIiGGPUzPrPfuXOuPDtbOD/odr3e4pOP6ts=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; /// <summary> /// 密钥 /// </summary> private static string privatekey = @"<RSAKeyValue><Modulus>ql+LrSBSyTeRQJN24dR76iRoNi8kRs7wYlwG0FRLuujGkR62HJTD/YM/7miAxCR0lufVGx6E0Ej46OSwIRsqwQo/C2WUnvjlbs/bGiiXkD7IC9lsmzQQEvVjTyrUMVzs7NQMoXwzvIiGGPUzPrPfuXOuPDtbOD/odr3e4pOP6ts=</Modulus><Exponent>AQAB</Exponent><P>3wM9IzYsOEa3eruVG0qjZ5IL4YleDVsCcTma9LT5cQitx4vAKUhYPuljH7ILl669cEWjmt/xGLw6uuOxD3VpYQ==</P><Q>w5MGBeFi3roc+SszgOJpl3QxinxIhcXsCXA/aXYXOtTMqcXCGuV3atSS+YDaP5zt0Nrvedrr6hHaoLfzMZyRuw==</Q><DP>E9eO7f4Y6xznoETmXFpEtadZ5UQ6mQea7QYKEnGzq+nwxEtb2pB0QYy0ZBKMU3+ZnU6k4te/9Mpyk0RE8bIpoQ==</DP><DQ>T4sZtQSRcOMja5hNj0sHBUmF6LxZxsbUFJapw9v64LuyLg63vra7liC1UnM80QijlQGmytnmf8IZOKr4Z6I1hw==</DQ><InverseQ>yfjwKeVxrr8Docp69gaEkoFFY1IwTw+Jpkf/LXIW+s5IZeqbhT7VoO5AXXMvhEGLi1IreNmzqEbhNVw3CudV6Q==</InverseQ><D>SfvBoMV3ja9WoQ8oQbrOsIdsxZLFEwaL9np17wOb+ydYCu6mMFUdornbCkFRIVufUWSM8wDWtcfqZt/f6BBvCL0P2xwBRuNWLP2fY8Yw/puyIlz5p2M3VcUBQcoZ63tX9NkQ3uaqFAlOKW0VrYDjviKPx5NhcR1glkdgYfDahUE=</D></RSAKeyValue>"; #endregion /// <summary> /// 加密保存文件 /// </summary> public static bool RSAEn(string message) { try { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(message.Length*8+11); //string ddd= rsa.ToXmlString(true); rsa.FromXmlString(publickey); byte[] dataToEncrypt = Encoding.UTF8.GetBytes(message); byte[] encryptedData = rsa.Encrypt(dataToEncrypt,false); return Write_Txt(encryptedData); } catch (Exception err) { return false; } } /// <summary> /// 获取解密后的文件内容 /// </summary> /// <returns>-1标示解密过程中出现了异常,-2标示物理文件读取失败</returns> public static string RSADe() { try { string temp = Read_txt(); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(temp.Length * 8 + 11); rsa.FromXmlString(privatekey); switch (temp) { case "-2": return "-2"; default: byte[] encryptedData = rsa.Decrypt(Convert.FromBase64String(temp), false); return Encoding.UTF8.GetString(encryptedData); } } catch (Exception) { return "-1"; } } #region 写文件 private static string path = System.Environment.CurrentDirectory + "\\type.data"; /// <summary> /// 写入文件 /// </summary> /// <param name="bytes"></param> /// <returns></returns> static protected bool Write_Txt(byte[] bytes) { try { File.WriteAllText(path,Convert.ToBase64String(bytes)); return true; } catch (Exception ex) { return false; } } #endregion #region 读文件 /// <summary> /// 读取文件 /// </summary> /// <returns></returns> static string Read_txt() { try { return File.ReadAllText(path, Encoding.UTF8); } catch (Exception ex) { return "-2"; } } #endregion }
本文来自博客园,作者:童心少年,转载请注明原文链接:https://www.cnblogs.com/makeblock/p/4275005.html