44 lines
1.5 KiB
JavaScript
44 lines
1.5 KiB
JavaScript
import CryptoJS from 'crypto-js';
|
||
import overAllConfig from '@/config.js'
|
||
|
||
/**
|
||
* AES-CBC 解密(从 Base64 中提取随机 IV)
|
||
* @param {string} base64Str - 加密后的 Base64 字符串(IV + 密文)
|
||
* @param {string} keyStr - 16 字节密钥字符串
|
||
* @returns {string} 解密后的明文
|
||
*/
|
||
export function decryptJson(encryptedBase64, base64Key = overAllConfig.AESKey) {
|
||
try {
|
||
// 1. Base64 解码密钥 & 数据
|
||
const key = CryptoJS.enc.Base64.parse(base64Key);
|
||
const combinedData = CryptoJS.enc.Base64.parse(encryptedBase64);
|
||
|
||
// 2. 提取 IV(前16字节 = 4 个 32bit Word)
|
||
const ivWords = combinedData.words.slice(0, 4);
|
||
const iv = CryptoJS.lib.WordArray.create(ivWords, 16);
|
||
|
||
// 3. 提取密文(剩余部分)
|
||
const ciphertextWords = combinedData.words.slice(4);
|
||
const ciphertext = CryptoJS.lib.WordArray.create(
|
||
ciphertextWords,
|
||
combinedData.sigBytes - 16
|
||
);
|
||
|
||
// 4. 解密
|
||
const decrypted = CryptoJS.AES.decrypt({
|
||
ciphertext
|
||
}, key, {
|
||
iv: iv,
|
||
mode: CryptoJS.mode.CBC,
|
||
padding: CryptoJS.pad.Pkcs7, // 等价于 Java 的 PKCS5Padding
|
||
});
|
||
|
||
const result = decrypted.toString(CryptoJS.enc.Utf8);
|
||
|
||
if (!result) throw new Error('解密失败,返回空字符串(可能密钥错误或格式错误)');
|
||
return result;
|
||
} catch (e) {
|
||
console.error('解密失败:', e);
|
||
return '';
|
||
}
|
||
} |