| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- function decryptAES(encrypted, secretKey) {
- try {
- // 1. 生成密钥(SHA-256)
- const key = CryptoJS.SHA256(secretKey).toString();
-
- // 2. Base64 解码
- const decodedData = decodeURIComponent(encrypted);
- const standardBase64 = decodedData.replace(/-/g, '+').replace(/_/g, '/');
- const paddedBase64 = standardBase64.padEnd(Math.ceil(standardBase64.length / 4) * 4,'=');
- const encryptedData = CryptoJS.enc.Base64.parse(paddedBase64);
-
- // 3. 提取 IV(前 16 字节)和密文(剩余部分)
- const iv = CryptoJS.lib.WordArray.create(encryptedData.words.slice(0, 4), 16);
- const ciphertext = CryptoJS.lib.WordArray.create(encryptedData.words.slice(4), encryptedData.sigBytes - 16);
-
- // 4. 解密(AES-CBC)
- const decrypted = CryptoJS.AES.decrypt(
- { ciphertext },
- CryptoJS.enc.Hex.parse(key),
- { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }
- );
-
- return decrypted.toString(CryptoJS.enc.Utf8);
- } catch (error) {
- console.error("[decryptAES] 解密失败:", error);
- throw new Error("解密失败,请检查密钥或密文是否正确");
- }
- }
- function encryptAES(plaintext, secretKey) {
- // 1. 生成密钥(SHA-256)
- const key = CryptoJS.SHA256(secretKey).toString();
-
- // 2. 生成随机 IV(16 字节)
- const iv = CryptoJS.lib.WordArray.random(16);
-
- // 3. 加密(AES-CBC)
- const encrypted = CryptoJS.AES.encrypt(
- plaintext,
- CryptoJS.enc.Hex.parse(key),
- { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }
- );
-
- // 4. 拼接 IV + 密文,并 Base64 编码
- const result = CryptoJS.lib.WordArray.create([
- ...iv.words,
- ...encrypted.ciphertext.words
- ], 16 + encrypted.ciphertext.sigBytes);
-
- const base64 = CryptoJS.enc.Base64.stringify(result);
- return base64
- .replace(/\+/g, '-') // 替换 + 为 -
- .replace(/\//g, '_') // 替换 / 为 _
- .replace(/=/g, ''); // 移除 =
- }
|