RSACrypt.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. using XC.Framework.Security.RSAUtil;
  6. namespace HaBookCms.Common.CryptHelper
  7. {
  8. /// <summary>
  9. /// RSA加密解密
  10. /// https://github.com/stulzq/RSAUtil
  11. /// </summary>
  12. public class RSACrypt
  13. {
  14. private readonly RsaPkcs1Util _RsaUtil;
  15. private readonly Encoding _encoding;
  16. /// <summary>
  17. /// 获得私钥和公钥
  18. /// [0]=privateKey 私钥
  19. /// [1]=publicKey 公钥
  20. /// </summary>
  21. /// <returns></returns>
  22. public static List<string> GetKey()
  23. {
  24. return RsaKeyGenerator.Pkcs1Key(2048, true);
  25. }
  26. /// <summary>
  27. /// 实例化
  28. /// </summary>
  29. /// <param name="encoding">编码类型</param>
  30. /// <param name="privateKey">私钥</param>
  31. /// <param name="publicKey">公钥</param>
  32. public RSACrypt(string privateKey, string publicKey)
  33. {
  34. _encoding = Encoding.UTF8;
  35. _RsaUtil = new RsaPkcs1Util(_encoding, publicKey, privateKey, 1024);
  36. }
  37. /// <summary>
  38. /// 加密
  39. /// </summary>
  40. /// <param name="code">加密代码</param>
  41. /// <returns></returns>
  42. public string Encrypt(string code)
  43. {
  44. return _RsaUtil.Encrypt(code, RSAEncryptionPadding.Pkcs1);
  45. }
  46. /// <summary>
  47. /// 解密
  48. /// </summary>
  49. /// <param name="code">解密代码</param>
  50. /// <returns></returns>
  51. public string Decrypt(string code)
  52. {
  53. return _RsaUtil.Decrypt(code, RSAEncryptionPadding.Pkcs1);
  54. }
  55. }
  56. }