javascript - NodeJS 加密模块:干净的密码重用
问题描述
我对 Node.js 中的加密模块有点陌生。我写了一个加密函数,它工作得很好,但看起来很糟糕。这有更好的方法来写这个吗?
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 加密所有值,但不是一次加密整个对象。有没有办法重构它以避免重复?
解决方案
试试这个:
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,
};
};
推荐阅读
- r - 闪亮的图像托管
- angular - Angular 8 CLI:在开发服务中禁用差异加载
- jar - 单独运行 WireMock 服务器
- java - 多线程期间更新方法的MongoDB错误
- awk - 使用 awk 或 sed 命令从文件的行中删除字母和括号
- c# - Azure Function v2 引用了 Newtonsoft.Json 版本高于 Microsoft.NET.Sdk.Functions 的项目
- c# - 我想针对一个项目创建多个页面帮助我
- perl - 为什么不让 -C 改变 $PWD ,就像通过 Perl 之类的脚本语言看到的那样?
- elasticsearch - ElasticSearch 中的父子关系 - 在所有子文档组合中搜索一个句子
- r - 从 sas 到 r 的新变量多个 if/then 代码