NodeJS 加密模块:干净的密码重用
NodeJS crypto module: clean cipher reuse
我对 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,
};
};
我对 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,
};
};