using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; namespace Common.Helper.Encryption { public class RsaHelper { private RSACryptoServiceProvider Csp { get; set; } private RSAParameters PrivateKey { get; set; } private RSAParameters PublicKey { get; set; } /// /// 公钥字符串 /// public string PublicKeyString { get; set; } private RsaHelper() { Csp = new RSACryptoServiceProvider(2048); //how to get the private key PrivateKey = Csp.ExportParameters(true); //and the public key ... PublicKey = Csp.ExportParameters(false); //converting the public key into a string representation { //we need some buffer var sw = new System.IO.StringWriter(); //we need a serializer var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); //serialize the key into the stream xs.Serialize(sw, PublicKey); //get the string from the stream PublicKeyString = sw.ToString(); } //converting it back { //get a stream from the string var sr = new System.IO.StringReader(PublicKeyString); //we need a deserializer var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); //get the object back from the stream PublicKey = (RSAParameters)xs.Deserialize(sr); } } static RsaHelper(){} public static RsaHelper Instance { get; } = new RsaHelper(); /// /// 加密数据 /// /// /// public string DesEncrypt(string keyWord) { //lets take a new CSP with a new 2048 bit rsa key pair //conversion for the private key is no black magic either ... omitted //we have a public key ... let's get a new csp and load that key Csp = new RSACryptoServiceProvider(); Csp.ImportParameters(PublicKey); //for encryption, always handle bytes... var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(keyWord); //apply pkcs#1.5 padding and encrypt our data var bytesCypherText = Csp.Encrypt(bytesPlainTextData, false); //we might want a string representation of our cypher text... base64 will do return Convert.ToBase64String(bytesCypherText); } /// /// 解密数据 /// /// /// public string DesDecrypt(string keyWord) { //first, get our bytes back from the base64 string ... var bytesCypherText = Convert.FromBase64String(keyWord); //we want to decrypt, therefore we need a csp and load our private key var csp = new RSACryptoServiceProvider(); csp.ImportParameters(PrivateKey); //decrypt and strip pkcs#1.5 padding var bytesPlainTextData = csp.Decrypt(bytesCypherText, false); //get our original plainText back... return System.Text.Encoding.Unicode.GetString(bytesPlainTextData); } } }