#region
/// <summary>
/// RSA获取公钥私钥
/// </summary>
/// <param name="str_PrivateKey"></param>
/// <param name="str_PublicKey"></param>
public void RSACreateKey(ref string str_PublicKey, ref string str_PrivateKey)
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(512);
//str_PublicKey = Convert.ToBase64String(RSA.ExportCspBlob(false));
//str_PrivateKey = Convert.ToBase64String(RSA.ExportCspBlob(true));
str_PublicKey = RSA.ToXmlString(false);
str_PrivateKey = RSA.ToXmlString(true);
}
/// <summary>
/// RSA加密
/// </summary>
/// <param name="source"></param>
/// <param name="str_PrivateKey"></param>
/// <param name="str_PublicKey"></param>
/// <returns></returns>
public string RSAEncrypt(string source, string str_PublicKey)
{
try
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString(str_PublicKey);
//str_PublicKey = Convert.ToBase64String(RSA.ExportCspBlob(false));
//str_PrivateKey = Convert.ToBase64String(RSA.ExportCspBlob(true));
byte[] DataToEncrypt = Encoding.UTF8.GetBytes(source);
byte[] bs = RSA.Encrypt(DataToEncrypt, false);
//str_PublicKey = Convert.ToBase64String(RSA.ExportCspBlob(false));
//str_PrivateKey = Convert.ToBase64String(RSA.ExportCspBlob(true));
string encrypttxt = Convert.ToBase64String(bs);
return encrypttxt;
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
/// <summary>
/// RSA解密
/// </summary>
/// <param name="strRSA"></param>
/// <param name="str_PrivateKey"></param>
/// <returns></returns>
public string RSADecrypt(string strRSA, string str_PrivateKey)
{
try
{
byte[] DataToDecrypt = Convert.FromBase64String(strRSA);
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString(str_PrivateKey);
//byte[] bsPrivatekey = Convert.FromBase64String(str_PrivateKey);
//RSA.ImportCspBlob(bsPrivatekey);
byte[] bsdecrypt = RSA.Decrypt(DataToDecrypt, false);
string strRE = Encoding.UTF8.GetString(bsdecrypt);
return strRE;
}
catch (CryptographicException e)
{
Console.WriteLine(e.ToString());
return null;
}
}
#endregion
.net中RSA的加密与解密
最新推荐文章于 2024-09-18 14:38:46 发布