// 调用
string tmpPriKey, tmpPubKey;
RsaHelper.GetPriPubKey(out tmpPriKey, out tmpPubKey);
string content = "这是im 223~! #苛sdkfj23";
string inString = RsaHelper.RsaEncrypt(tmpPubKey, content);
string outString = RsaHelper.RsaDecrypt(tmpPriKey, inString);
var tmpBb = RsaHelper.RsaSignData(tmpPriKey, content);
var tmpResult = RsaHelper.RsaVerifyData(tmpPubKey, content, tmpBb);
/// <summary>
/// Rsa加解密/// </summary>
public class RsaHelper
{
/// <summary>
/// 获取私钥、公钥
/// </summary>
/// <param name="priKey"></param>
/// <param name="pubKey"></param>
public static void GetPriPubKey(out string priKey, out string pubKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
priKey = rsa.ToXmlString(true);
pubKey = rsa.ToXmlString(false);
}
/// <summary>
/// RSA加密
/// </summary>
/// <param name="publickey"></param>
/// <param name="content"></param>
/// <returns></returns>
public static string RsaEncrypt(string publickey, string content)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(publickey);
var 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)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(privateKey);
var cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
return Encoding.UTF8.GetString(cipherbytes);
}
/// <summary>
/// RSA私钥签名
/// </summary>
/// <param name="privatekey"></param>
/// <param name="content"></param>
/// <returns></returns>
public static byte[] RsaSignData(string privatekey, string content)
{
RSACryptoServiceProvider oRSA3 = new RSACryptoServiceProvider();
oRSA3.FromXmlString(privatekey);
byte[] messagebytes = Encoding.UTF8.GetBytes(content);
byte[] aOutput = oRSA3.SignData(messagebytes, "SHA1");
return aOutput;
}
/// <summary>
/// RSA公钥验证
/// </summary>
/// <param name="publickey"></param>
/// <param name="content"></param>
/// <param name="messagebytes"></param>
/// <returns></returns>
public static bool RsaVerifyData(string publickey, string content, byte[] messagebytes)
{
RSACryptoServiceProvider oRSA4 = new RSACryptoServiceProvider();
oRSA4.FromXmlString(publickey);
bool bVerify = oRSA4.VerifyData(Encoding.UTF8.GetBytes(content), "SHA1", messagebytes);
return bVerify;
}
}