Node.js NodeJS解密数据损坏的原始数据
我使用AES-266-CBC加密数据:Node.js NodeJS解密数据损坏的原始数据,node.js,cryptography,aes,Node.js,Cryptography,Aes,我使用AES-266-CBC加密数据: const iv = crypto.randomBytes(8).toString('hex'); const encrypt = (text: string): string => { log('encrypt'); const cipher = crypto.createCipheriv('aes-256-cbc', ENCRYPTION_KEY, iv); let encrypted = cipher.update(text, '
const iv = crypto.randomBytes(8).toString('hex');
const encrypt = (text: string): string => {
log('encrypt');
const cipher = crypto.createCipheriv('aes-256-cbc', ENCRYPTION_KEY, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
};
const decrypt = (text: string): string => {
log('decrypt');
const decipher = crypto.createDecipheriv('aes-256-cbc', ENCRYPTION_KEY, iv);
let decrypted = decipher.update(text, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
};
一切都很完美,这意味着如果我用这个:
const data = JSON.stringify({
user: 'MHF',
info: {
age: 23,
family: 'HF'
}
});
const encrypted = encrypt(data);
console.log('encrypted: %s', encrypted);
const decrypted = decrypt(encrypted);
console.log('decrypted: %s', decrypted);
问题是,当我通过post请求http发送加密字符串时,如下所示:
POST {{baseUrl}}/v1/user-register
Content-Type: application/json
Content-Encrypted: AES
{"payLoad": "3f1d1584b0e1976ccea311b5fbe0b2aee1034198a582a3b8bcc773c175e91bb0ceda6b9fb88aff11a892fa7adb83d432"}
我有一个由一些不正确的字符解密的数据,如:r!!(h\x7F!o#L\x19\x10~\x7F“jnfo”:{“年龄”:23,“家庭”:“高频”} 为什么通过加密数据进行post请求时会得到此结果?
这是什么:'r!!(h\x7F!o\L\x19\x10~\x7F“j”?多亏了@Topaco和@Michael Fehr
生成和使用IV是我的一个大错误,加密和解密需要相同的IV。看起来您使用的是不同的IV。通常在加密过程中,会生成一个随机IV,并将其与密文一起发送给收件人(通常是串联的)。@Topaco Yes我将相同的IV发送给两个函数:const IV=crypto.randomBytes(8).toString('hex');@mh f:很抱歉,您使用了生成随机iv的同一个函数来加密和解密,所以在解密端它将与加密端使用的iv不同-这就是Topaco提出的观点。@Topaco@Michael Fehr您是对的,这是我的一个大错误。无论如何,感谢你们两位