NodeJS解密数据损坏的原始数据

问题描述

我使用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,'utf8','hex');

  encrypted += cipher.final('hex');
  return encrypted;
};

const decrypt = (text: string): string => {
  log('decrypt');

  const decipher = crypto.createDecipheriv('aes-256-cbc',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);

问题是当我通过发帖请求http发送加密的字符串时,如下所示:

POST {{baseUrl}}/v1/user-register
Content-Type: application/json
Content-Encrypted: AES

{"payLoad": "3f1d1584b0e1976ccea311b5fbe0b2aee1034198a582a3b8bcc773c175e91bb0ceda6b9fb88aff11a892fa7adb83d432"}

我有一些通过不正确的字符解密的数据,如下所示:
'r !!(h \ x7F!o#L \ x19 \ x10〜\ x7F“ jnfo”:{“ age”:23,“ family”:“ HF”}}''

为什么当我通过加密数据发出发帖请求时会得到此结果?
这是什么:'r !!(h \ x7F!o#L \ x19 \ x10〜\ x7F“ j”?

解决方法

感谢@Topaco和@Michael Fehr
这是我关于生成和使用IV的大错误