SMUtil.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using Org.BouncyCastle.Utilities.Encoders;
  2. namespace Admin.NET.Core;
  3. /// <summary>
  4. /// SM工具类
  5. /// </summary>
  6. public class SMUtil
  7. {
  8. public static string PublicKey = App.GetConfig<string>("Crypto:PublicKey"); // 公钥
  9. public static string PrivateKey = App.GetConfig<string>("Crypto:PrivateKey"); // 私钥
  10. /// <summary>
  11. /// SM2加密
  12. /// </summary>
  13. /// <param name="plainText"></param>
  14. /// <returns></returns>
  15. public static string SM2Encrypt(string plainText)
  16. {
  17. byte[] sourceData = Encoding.Default.GetBytes(plainText);
  18. return SM2Util.Encrypt(Hex.Decode(PublicKey), sourceData);
  19. }
  20. /// <summary>
  21. /// SM2解密
  22. /// </summary>
  23. /// <param name="cipherText"></param>
  24. /// <returns></returns>
  25. public static string SM2Decrypt(string cipherText)
  26. {
  27. return Encoding.Default.GetString(SM2Util.Decrypt(Hex.Decode(PrivateKey), Hex.Decode(cipherText)));
  28. }
  29. /// <summary>
  30. /// SM4加密(ECB)
  31. /// </summary>
  32. /// <param name="plainText"></param>
  33. /// <returns></returns>
  34. public static string SM4EncryptECB(string plainText)
  35. {
  36. var sm4 = new SM4Util();
  37. return sm4.Encrypt_ECB(plainText);
  38. }
  39. /// <summary>
  40. /// SM4解密(ECB)
  41. /// </summary>
  42. /// <param name="cipherText"></param>
  43. /// <returns></returns>
  44. public static string SM4DecryptECB(string cipherText)
  45. {
  46. var sm4 = new SM4Util();
  47. return sm4.Decrypt_ECB(cipherText);
  48. }
  49. /// <summary>
  50. /// SM4加密(CBC)
  51. /// </summary>
  52. /// <param name="plainText"></param>
  53. /// <returns></returns>
  54. public static string SM4EncryptCBC(string plainText)
  55. {
  56. var sm4 = new SM4Util();
  57. return sm4.Encrypt_CBC(plainText);
  58. }
  59. /// <summary>
  60. /// SM4解密(CBC)
  61. /// </summary>
  62. /// <param name="cipherText"></param>
  63. /// <returns></returns>
  64. public static string SM4DecryptCBC(string cipherText)
  65. {
  66. var sm4 = new SM4Util();
  67. return sm4.Decrypt_CBC(cipherText);
  68. }
  69. public static string StrToHex(string str)
  70. {
  71. return Encoding.ASCII.GetString(Hex.Encode(Encoding.UTF8.GetBytes(str))).ToUpper();
  72. }
  73. }