Javascript NodeJS加密模块:干净的密码重用

Javascript NodeJS加密模块:干净的密码重用,javascript,node.js,encryption,cryptography,cryptojs,Javascript,Node.js,Encryption,Cryptography,Cryptojs,我对Node中的加密模块有点陌生。我写了一个加密函数,它工作得很好,但看起来很糟糕。有更好的方法写这个吗 const encrypt = data => { const iv = crypto.randomBytes(16); const key = crypto.randomBytes(32).toString('hex').slice(0, 32); const cipher1 = crypto.createCipheriv(algorithm, new Buffer(k

我对Node中的加密模块有点陌生。我写了一个加密函数,它工作得很好,但看起来很糟糕。有更好的方法写这个吗

const encrypt = data => {
  const iv = crypto.randomBytes(16);
  const key = crypto.randomBytes(32).toString('hex').slice(0, 32);

  const cipher1 = crypto.createCipheriv(algorithm, new Buffer(key), iv);
  const cipher2 = crypto.createCipheriv(algorithm, new Buffer(key), iv);
  const cipher3 = crypto.createCipheriv(algorithm, new Buffer(key), iv);

  const encryptedFile = Buffer.concat([cipher1.update(data.file), cipher1.final()]);
  const encryptedFileName = Buffer.concat([cipher2.update(data.fileName), cipher2.final()]).toString('hex');
  const encryptedId = Buffer.concat([cipher3.update(data.Id), cipher3.final()]).toString('hex');

  return {
    file: encryptedFile,
    fileName: encryptedFileName,
    id: iv.toString('hex') + ':' + encryptedId.toString('hex'),
    key
  };
};
输入是此结构的一个对象:

{
  file: <Buffer>,
  fileName: <String>,
  Id: <String>
}
{
档案:,
文件名:,
身份证件:
}
我需要用相同的key+iv加密所有的值,但不能同时加密整个对象。有没有办法重构此文件以避免重复?

尝试以下方法:

const encrypt = (data, key, iv) => {
    const cipher = crypto.createCipheriv(algorithm, new Buffer(key), iv);

    return Buffer.concat([cipher.update(data), cipher.final()]);
};

const encrypt = data => {
    const iv = crypto.randomBytes(16);
    const key = crypto
      .randomBytes(32)
      .toString('hex')
      .slice(0, 32);

    return {
      file: encrypt(data.file, key, iv),
      fileName: encrypt(data.fileName, key, iv).toString('hex'),
      id: `${iv.toString('hex')}:${encrypt(data.Id, key, iv).toString('hex')}`,
      key,
    };
  };