这篇文章主要介绍了C#中RSA加密与解密的实例代码,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
1. RSA加密与解密 -- 使用公钥加密、私钥解密
public class RSATool
{
public string Encrypt(string strText, string strPublicKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(strPublicKey);
byte[] byteText = Encoding.UTF8.GetBytes(strText);
byte[] byteEntry = rsa.Encrypt(byteText, false);
return Convert.ToBase64String(byteEntry);
}
public string Decrypt(string strEntryText,string strPrivateKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(strPrivateKey);
byte[] byteEntry = Convert.FromBase64String(strEntryText);
byte[] byteText = rsa.Decrypt(byteEntry, false);
return Encoding.UTF8.GetString(byteText);
}
public Dictionary<string,string> GetKey()
{
Dictionary<string, string> dictKey = new Dictionary<string, string>();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
dictKey.Add("PublicKey", rsa.ToXmlString(false));
dictKey.Add("PrivateKey", rsa.ToXmlString(true));
return dictKey;
}
}
测试:
RSATool myRSA = new RSATool();
Dictionary<string, string> dictK = new Dictionary<string, string>();
dictK = myRSA.GetKey();
string strText = "123456";
Console.WriteLine("要加密的字符串是:{0}", strText);
string str1 = myRSA.Encrypt("123456", dictK["PublicKey"]);
Console.WriteLine("加密后的字符串:{0}", str1);
string str2 = myRSA.Decrypt(str1, dictK["PrivateKey"]);
Console.WriteLine("解密后的字符串:{0}", str2);
2. RSA加密与解密 -- 使用同一个密钥容器进行加密与解密
public class RSAToolX
{
public string Encrypt(string strText)
{
CspParameters CSApars = new CspParameters();
CSApars.KeyContainerName = "Test001";
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(CSApars);
byte[] byteText = Encoding.UTF8.GetBytes(strText);
byte[] byteEntry = rsa.Encrypt(byteText, false);
return Convert.ToBase64String(byteEntry);
}
public string Decrypt(string strEntryText)
{
CspParameters CSApars = new CspParameters();
CSApars.KeyContainerName = "Test001";
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(CSApars);
byte[] byteEntry = Convert.FromBase64String(strEntryText);
byte[] byteText = rsa.Decrypt(byteEntry, false);
return Encoding.UTF8.GetString(byteText);
}
}
测试 :
RSAToolX myRSA = new RSAToolX();
string strText = "123456";
Console.WriteLine("要加密的字符串是:{0}", strText);
string str1 = myRSA.Encrypt("123456");
Console.WriteLine("加密后的字符串:{0}", str1);
string str2 = myRSA.Decrypt(str1);
Console.WriteLine("解密后的字符串:{0}", str2);
总结
以上所述是小编给大家介绍的C#中RSA加密与解密的实例详解,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
沃梦达教程
本文标题为:C#中RSA加密与解密的实例详解
猜你喜欢
- Unity Shader实现模糊效果 2023-04-27
- Oracle中for循环的使用方法 2023-07-04
- c# 模拟线性回归的示例 2023-03-14
- 如何使用C# 捕获进程输出 2023-03-10
- user32.dll 函数说明小结 2022-12-26
- Unity3D实现渐变颜色效果 2023-01-16
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- .NET CORE DI 依赖注入 2023-09-27
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16