非对称加解密
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Library { /// <summary> /// 非对称加解密 /// </summary> public class RSAtoData { /// <summary> /// 公钥,私钥 /// </summary> private static string priv = string.Empty, pub = string.Empty; /// <summary> /// 生成公,私钥 /// </summary> static RSAtoData() { if (string.IsNullOrEmpty(priv) && string.IsNullOrEmpty(pub)) { RSACryptoServiceProvider rsaobj = new RSACryptoServiceProvider(); priv = Convert.ToBase64String(rsaobj.ExportCspBlob(true)); pub = Convert.ToBase64String(rsaobj.ExportCspBlob(false)); } } /// <summary> /// 加密(使用公钥) /// </summary> /// <param name="needEncryptStr">需加密数据</param> /// <returns></returns> public string EncryptRSA(string needEncryptStr) { string result = string.Empty; if (!string.IsNullOrEmpty(needEncryptStr)) { RSACryptoServiceProvider rsaobj = new RSACryptoServiceProvider(); byte[] byteDataSecret = Encoding.UTF8.GetBytes(needEncryptStr); rsaobj.ImportCspBlob(Convert.FromBase64String(pub)); var EncryptResult = rsaobj.Encrypt(byteDataSecret, false); result = Convert.ToBase64String(EncryptResult); } return result; } /// <summary> /// 解密(使用私钥) /// </summary> /// <param name="needDecryptData">需解密数据</param> /// <returns></returns> public string DecryptRSA(string needDecryptData) { string result = string.Empty; if (!string.IsNullOrEmpty(needDecryptData)) { byte[] EncryptData = Convert.FromBase64String(needDecryptData); RSACryptoServiceProvider rsaobj = new RSACryptoServiceProvider(); rsaobj.ImportCspBlob(Convert.FromBase64String(priv)); var EncryptResult = rsaobj.Decrypt(EncryptData, false); result = Encoding.UTF8.GetString(EncryptResult); } return result; } } }
RSA实现数字签名
/// <summary> /// 私钥签名 /// </summary> /// <param name="str"></param> /// <param name="privatekey"></param> /// <returns></returns> private string CreateSign(string str,string privatekey) { using (RSACryptoServiceProvider oRSA1 = new RSACryptoServiceProvider()) { oRSA1.FromXmlString(privatekey); byte[] messagebytes = Encoding.UTF8.GetBytes(str); byte[] AOutput = oRSA1.SignData(messagebytes, new SHA1CryptoServiceProvider()); return Convert.ToBase64String(AOutput); } }
/// <summary> /// 验证签名 /// </summary> /// <param name="str"></param> /// <param name="SignedData"></param> /// <param name="publicKey"></param> /// <returns></returns> private bool VerifySigned(string str, string SignedData, string publicKey) { using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider()) { RSAalg.FromXmlString(publicKey); byte[] dataToVerifyBytes = Encoding.UTF8.GetBytes(str); byte[] signedDataBytes = Convert.FromBase64String(SignedData); return RSAalg.VerifyData(dataToVerifyBytes, new SHA1CryptoServiceProvider(), signedDataBytes); } }