我正在经历nestjs Encryption and Hashing documentation它显示了这一点:
import { createCipheriv, randomBytes, scrypt } from 'crypto';
import { promisify } from 'util';
const iv = randomBytes(16);
const password = 'Password used to generate key';
// The key length is dependent on the algorithm.
// In this case for aes256, it is 32 bytes.
const key = (await promisify(scrypt)(password, 'salt', 32)) as Buffer;
const cipher = createCipheriv('aes-256-ctr', key, iv);
const textToEncrypt = 'Nest';
const encryptedText = Buffer.concat([
cipher.update(textToEncrypt),
cipher.final(),
]);
我无法理解这一行:
const key = (await promisify(scrypt)(password, 'salt', 32)) as Buffer;
这是我的问题:
- 这条线在做什么?
- 为什么我必须这样做?在其他教程中,他们只是使用 key 而不是执行此行。“盐”是什么意思?在方法文档中我只找到了
arg2: BinaryLike
- “盐”是什么意思?在方法文档中我只找到了
arg2: BinaryLike
最佳答案
crypto.scrypt(password, salt, keylen[, options], callback)
crypto.scrypt
是一个采用 "error-first" callback function 的函数:scrypt
将异步派生 key 并调用回调方法返回值,并向回调传递两个参数 err
和 data
(这里的data
是一个记录为衍生 key
的缓冲区)。
util.promisfy
是一个接受 Function 并返回 Function 的实用程序:您向其传递一个使用错误优先回调的 Function,它返回一个返回 Promise 的 Function,而不是传回回调方法。这允许您使用 await
(如示例代码中所示)以及 then
链接和 Promise.all
等工具。
const key = (await promisify(scrypt)(password, 'salt', 32)) as Buffer;
// This ^^^^^^^^^^^^^^^^^ is just a function based on scrypt.
Salt是每条记录存储的随机加密值的通用术语;对于scrypt
,特别是盐“应该尽可能唯一”,建议“盐是随机的,并且至少有 16 个字节长”。更多信息请访问 crypto.SE或Wikipedia .
关于node.js - NestJS 加密 : What is the purpose of the promisify(scrypt)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68898796/