温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#中RSA加密与解密的实例详解

发布时间:2020-09-17 03:42:52 来源:脚本之家 阅读:220 作者:在代码的世界里游走 栏目:编程语言

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);

C#中RSA加密与解密的实例详解

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加密与解密的实例详解,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI