VerifyPasswordEncryptUtils.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using Org.BouncyCastle.Crypto.Parameters;
  2. using Org.BouncyCastle.Security;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace PTMedicalInsurance.Common.SMLib
  10. {
  11. class VerifyPasswordEncryptUtils
  12. {
  13. public static string encrypt(string plaintext, string secKey)
  14. {
  15. byte[] keyBytes = Encoding.UTF8.GetBytes(secKey);
  16. if (keyBytes.Length != 16)
  17. throw new ArgumentException("Key must be 16 bytes (ASCII string of length 16).");
  18. // 生成随机 IV(16 字节)
  19. byte[] iv = new byte[16];
  20. using (var rng = RandomNumberGenerator.Create())
  21. rng.GetBytes(iv);
  22. byte[] plainBytes = Encoding.UTF8.GetBytes(plaintext);
  23. // 使用 SM4/CBC/PKCS7
  24. var keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  25. var ivParam = new ParametersWithIV(keyParam, iv);
  26. var cipher = CipherUtilities.GetCipher("SM4/CBC/PKCS7Padding");
  27. cipher.Init(true, ivParam); // true = encrypt
  28. byte[] encrypted = cipher.DoFinal(plainBytes);
  29. // 拼接 IV + 密文
  30. byte[] combined = new byte[iv.Length + encrypted.Length];
  31. Buffer.BlockCopy(iv, 0, combined, 0, iv.Length);
  32. Buffer.BlockCopy(encrypted, 0, combined, iv.Length, encrypted.Length);
  33. // 返回 Base64(与 Java 一致)
  34. return Convert.ToBase64String(combined);
  35. }
  36. }
  37. }