Files
jobslink-user-clent/untils/authService.js
2025-05-16 21:04:01 +08:00

44 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 '';
}
}