crypto.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. function decryptAES(encrypted, secretKey) {
  2. try {
  3. // 1. 生成密钥(SHA-256)
  4. const key = CryptoJS.SHA256(secretKey).toString();
  5. // 2. Base64 解码
  6. const decodedData = decodeURIComponent(encrypted);
  7. const standardBase64 = decodedData.replace(/-/g, '+').replace(/_/g, '/');
  8. const paddedBase64 = standardBase64.padEnd(Math.ceil(standardBase64.length / 4) * 4,'=');
  9. const encryptedData = CryptoJS.enc.Base64.parse(paddedBase64);
  10. // 3. 提取 IV(前 16 字节)和密文(剩余部分)
  11. const iv = CryptoJS.lib.WordArray.create(encryptedData.words.slice(0, 4), 16);
  12. const ciphertext = CryptoJS.lib.WordArray.create(encryptedData.words.slice(4), encryptedData.sigBytes - 16);
  13. // 4. 解密(AES-CBC)
  14. const decrypted = CryptoJS.AES.decrypt(
  15. { ciphertext },
  16. CryptoJS.enc.Hex.parse(key),
  17. { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }
  18. );
  19. return decrypted.toString(CryptoJS.enc.Utf8);
  20. } catch (error) {
  21. console.error("[decryptAES] 解密失败:", error);
  22. throw new Error("解密失败,请检查密钥或密文是否正确");
  23. }
  24. }
  25. function encryptAES(plaintext, secretKey) {
  26. // 1. 生成密钥(SHA-256)
  27. const key = CryptoJS.SHA256(secretKey).toString();
  28. // 2. 生成随机 IV(16 字节)
  29. const iv = CryptoJS.lib.WordArray.random(16);
  30. // 3. 加密(AES-CBC)
  31. const encrypted = CryptoJS.AES.encrypt(
  32. plaintext,
  33. CryptoJS.enc.Hex.parse(key),
  34. { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }
  35. );
  36. // 4. 拼接 IV + 密文,并 Base64 编码
  37. const result = CryptoJS.lib.WordArray.create([
  38. ...iv.words,
  39. ...encrypted.ciphertext.words
  40. ], 16 + encrypted.ciphertext.sigBytes);
  41. const base64 = CryptoJS.enc.Base64.stringify(result);
  42. return base64
  43. .replace(/\+/g, '-') // 替换 + 为 -
  44. .replace(/\//g, '_') // 替换 / 为 _
  45. .replace(/=/g, ''); // 移除 =
  46. }