54 lines
1.8 KiB
JavaScript
54 lines
1.8 KiB
JavaScript
|
|
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(''))
|
|||
|
|
}
|