EncryptUtil.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import CryptoES from "crypto-es";
  2. export class EncryptUtil {
  3. private static _key: string = "";
  4. private static _iv: CryptoES.lib.WordArray = null;
  5. // 初始化加密库
  6. static initCrypto(key: string, iv: string) {
  7. this._key = key;
  8. this._iv = CryptoES.enc.Hex.parse(iv);
  9. }
  10. // MD5加密
  11. static md5(msg: string) {
  12. return CryptoES.MD5(msg).toString();
  13. }
  14. // AES加密
  15. static aesEncrypt(msg: string, key?: string, iv?: string): string {
  16. const keyUtf8 = CryptoES.enc.Utf8.parse(key);
  17. const ivUtf8 = CryptoES.enc.Utf8.parse(iv);
  18. const encryptedData = CryptoES.AES.encrypt(msg, keyUtf8, {
  19. iv: ivUtf8,
  20. mode: CryptoES.mode.CBC,
  21. padding: CryptoES.pad.Pkcs7,
  22. });
  23. return encryptedData.toString();
  24. }
  25. // AES解密
  26. static aesDecrypt(str: string, key?: string, iv?: string): string {
  27. const decrypted = CryptoES.AES.decrypt(
  28. str,
  29. this._key,
  30. {
  31. iv: this._iv,
  32. format: this.JsonFormatter
  33. },
  34. );
  35. return decrypted.toString(CryptoES.enc.Utf8);
  36. }
  37. private static JsonFormatter = {
  38. stringify: function (cipherParams: any) {
  39. const jsonObj: any = { ct: cipherParams.ciphertext.toString(CryptoES.enc.Base64) };
  40. if (cipherParams.iv) {
  41. jsonObj.iv = cipherParams.iv.toString();
  42. }
  43. if (cipherParams.salt) {
  44. jsonObj.s = cipherParams.salt.toString();
  45. }
  46. return JSON.stringify(jsonObj);
  47. },
  48. parse: function (jsonStr: any) {
  49. const jsonObj = JSON.parse(jsonStr);
  50. const cipherParams = CryptoES.lib.CipherParams.create(
  51. { ciphertext: CryptoES.enc.Base64.parse(jsonObj.ct) },
  52. );
  53. if (jsonObj.iv) {
  54. cipherParams.iv = CryptoES.enc.Hex.parse(jsonObj.iv)
  55. }
  56. if (jsonObj.s) {
  57. cipherParams.salt = CryptoES.enc.Hex.parse(jsonObj.s)
  58. }
  59. return cipherParams;
  60. },
  61. };
  62. }