欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-11 12:06:40
1.  rsa加密与解密  --  使用公钥加密、私钥解密 public class rsatool { public s...

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加密与解密的实例详解,希望对大家有所帮助