gpt4 book ai didi

node.js - bcrypt node.js(自动生成盐和哈希值)

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:32 26 4
gpt4 key购买 nike

在将用户密码存储在数据库中之前,我使用以下代码对用户密码进行哈希处理(并希望加盐)。

// hash the password before the user is saved
ConsultantSchema.pre('save', function(next) {
var user = this;

// hash the password only if the password has been changed or user is new
if (!user.isModified('password')) return next();

// generate the hash
bcrypt.hash(user.password, null, null, function(err, hash) {

if (err) {
logger.error("bcrypt.hash "+err);
return next(err);
}

// change the password to the hashed version
user.password = hash;
next();
});
});

我感到困惑的是这部分

bcrypt.hash(user.password, null, null, function(err, hash) {

我从教程中获得了这段代码,并且我经常看到它在寻找答案。根据 bcrypt 的文档( https://www.npmjs.com/package/bcrypt ),我期望以下代码

const saltrounds = 10;
bcrypt.hash(user.password, saltRounds, function(err, hash) {

可以工作,但这会破坏我的程序而不会出现错误。

我的问题是:为什么有两个“空”参数?它们是做什么用的?哈希值是否基于带有两个空值的代码进行加盐处理?

预先感谢您的帮助!

最佳答案

bcrypt 之间存在差异和 bcrypt-nodejs 。以下代码来自 npmjs.com 上的文档。

bcrypt 哈希

bcrypt.hash(myPlaintextPassword, salt, function(err, hash)

bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash)

bcrypt-nodejs 哈希

bcrypt.hash(myPlaintextPassword, null, null, function(err, hash)

说明

您正在查看 bcrypt 的文档,而不是 bcrypt-nodejs。如果您使用的是node.js,您很可能想使用bcrypt-nodejs。我有多个项目利用它的功能。两个 null 字段用于盐和进度:

  • salt - [必需] - 用于散列密码的盐。
  • progress - 在哈希计算期间调用的回调以表示进度

关于node.js - bcrypt node.js(自动生成盐和哈希值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44797213/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com