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

时间:2018-10-08 03:52:34

标签: 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(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>
}

我需要用相同的键+ iv加密所有值,而不是一次加密整个对象。有没有一种方法可以重构它以避免重复?

1 个答案:

答案 0 :(得分:0)

尝试一下:

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,
    };
  };