crypto.js 1.9 KB

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