node.js - NestJS 加密 : What is the purpose of the promisify(scrypt)?

标签 node.js typescript nestjs cryptojs

我正在经历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;

这是我的问题:

  1. 这条线在做什么?
  2. 为什么我必须这样做?在其他教程中,他们只是使用 key 而不是执行此行。“盐”是什么意思?在方法文档中我只找到了 arg2: BinaryLike
  3. “盐”是什么意思?在方法文档中我只找到了 arg2: BinaryLike

最佳答案

crypto.scrypt(password, salt, keylen[, options], callback)

crypto.scrypt是一个采用 "error-first" callback function 的函数:scrypt异步派生 key 并调用回调方法返回值,并向回调传递两个参数 errdata (这里的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.SEWikipedia .

关于node.js - NestJS 加密 : What is the purpose of the promisify(scrypt)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68898796/

相关文章:

node.js - 在 Electron react 应用程序中导入 whatsapp-web.js nodejs 模块的问题

javascript - 使用 typescript 和默认值解构嵌套参数

typescript - 参数隐式具有 'any' 类型

database - 数据库连接是否总是在 NestJS + TypeORM 中打开?

javascript - forRoot 和 forFeature 的区别 [Nest JS]

node.js - 从 node.js 中的外部网页获取所有图像 url 的最佳方法是什么

javascript - NodeJS 集群 - 它们共享什么吗?

javascript - node.js+express+jade : style. css 内部服务器错误 500

javascript - "this"在 map 运算符 Angular 中未定义

javascript - 在 NestJS 中直接使用 HTTP2