Files
qnc-webview-v3/src/utils/crypto.js
2025-12-16 12:33:02 +08:00

54 lines
1.8 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'
// AES CBC 加密IV 拼接在密文前面,并进行 Base64 编码// AES CBC 加密IV 拼接在密文前面,并进行 Base64 编码
export function aesEncrypt(plainText, hexKey) {
// 转换密钥为WordArray
const key = CryptoJS.enc.Hex.parse(hexKey)
// 生成一个随机的IV
const iv = generateRandomIV() // 生成 16 字节的随机 IV
// 加密
const encrypted = CryptoJS.AES.encrypt(plainText, key, {
iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
})
// 拼接IV和密文IV在前密文在后最后Base64编码
const ivAndCipherText = iv.concat(encrypted.ciphertext)
return CryptoJS.enc.Base64.stringify(ivAndCipherText)
}
// AES CBC 解密IV 在密文前面,并且 Base64 解码
export function aesDecrypt(base64CipherText, hexKey) {
// 转换密钥为WordArray
const key = CryptoJS.enc.Hex.parse(hexKey)
// Base64解码并转换为WordArray
const cipherParams = CryptoJS.enc.Base64.parse(base64CipherText)
// 提取 IV前 16 字节)
const iv = cipherParams.clone().words.slice(0, 4) // 16 字节的 IV 对应 4 个字(每个字 4 字节)
// 提取密文
const cipherText = cipherParams.clone().words.slice(4) // 从第 4 个字开始到最后的密文
// 解密
const decrypted = CryptoJS.AES.decrypt({ ciphertext: CryptoJS.lib.WordArray.create(cipherText) }, key, {
iv: CryptoJS.lib.WordArray.create(iv),
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
})
// 返回解密后的明文
return decrypted.toString(CryptoJS.enc.Utf8)
}
function generateRandomIV() {
const iv = []
for (let i = 0; i < 16; i++) { // 16 字节的 IV
iv.push(Math.floor(Math.random() * 256)) // 0-255 的随机数
}
return CryptoJS.enc.Hex.parse(iv.map(b => b.toString(16).padStart(2, '0')).join(''))
}