nodejs代码
const crypto = require('crypto');
const secretKey = '1234567890123456'; // 16 字节的密钥,必须为 16/24/32 字节
const iv = crypto.randomBytes(16); // 生成随机初始向量
// AES 加密函数
function AES_encrypt(text) {
const cipher = crypto.createCipheriv('aes-128-cbc', Buffer.from(secretKey), iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return {
iv: iv.toString('hex'),
content: encrypted
};
}
// AES 解密函数
function AES_decrypt(encryptedText, ivHex) {
console.log(encryptedText, ivHex);
const decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(secretKey), Buffer.from(ivHex, 'hex'));
// let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
let decrypted = decipher.update(Buffer.from(encryptedText, 'base64'), 'binary', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// //测试加密
// const encryptedText = { account: '111222', password: 'booway1234' };
// const encrypted = AES_encrypt(JSON.stringify(encryptedText));
// console.log(encrypted); // { iv: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6', content: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6' }
// console.log(JSON.stringify(encrypted)); // {"iv":"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6","content":"a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6"}
// //测试解密
// const decryptedText = AES_decrypt(encrypted.content, encrypted.iv);
// console.log(JSON.parse(decryptedText)); // { account: '111222', password: 'booway1234' }
// console.log(decryptedText); // {"account":"111222","password":"booway1234"}
exports.AES_encrypt = AES_encrypt;
exports.AES_decrypt = AES_decrypt;
vue代码
import CryptoJS from 'crypto-js';
// 定义密钥,确保这个密钥安全且不被泄露
const secretKey = '1234567890123456'; // 16 字节的密钥
// AES 加密函数
export function AES_encrypt(data) {
console.log('type', typeof data);
// 生成随机IV
const iv = CryptoJS.lib.WordArray.random(16); // 生成随机的16字节IV
const encrypted = CryptoJS.AES.encrypt(
JSON.stringify(data),
CryptoJS.enc.Utf8.parse(secretKey),
{
iv: iv, // 使用随机生成的IV
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
}
);
// 返回 IV 和加密后的内容
return {
iv: iv.toString(CryptoJS.enc.Hex),
content: encrypted.toString()
};
}
// AES 解密函数
export function AES_decrypt(encryptedData) {
const iv = CryptoJS.enc.Hex.parse(encryptedData.iv);
const decrypted = CryptoJS.AES.decrypt(encryptedData.content, CryptoJS.enc.Utf8.parse(secretKey), {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return JSON.parse(decrypted.toString(CryptoJS.enc.Utf8)); // 返回解密后的对象
}
在测试前端进行请求加密,后端进行解密时,始终解密报错,提示 nodejs Error: error:1C80006B:Provider routines::wrong final block length
在反复确认了两端iv一致,密钥一致,加密方式一致,一直在问GPT,折腾了许久都没解决 最后发现GPT有段描述注意到了,是前端用的base64编码,而后端一直在用hex格式,导致后端始终解密失败,最后修改调试成功了~