【问题标题】:bcrypt node.js (auto-gen a salt and hash)bcrypt node.js(自动生成盐和哈希)
【发布时间】:2017-06-28 08:21:20
【问题描述】:

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

// 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) {

正在工作,但这会在没有错误的情况下破坏我的程序。

我的问题是: 为什么有两个“空”参数?它们是干什么用的? 哈希是根据两个空值的代码加盐的吗?

提前感谢您的帮助!

【问题讨论】:

  • 你用的是什么版本的nodejs和bcrypt模块?

标签: node.js hash bcrypt salt saltedhash


【解决方案1】:

bcryptbcrypt-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:

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

【讨论】:

    【解决方案2】:

    我已经使用加密库进行哈希处理,效果很好。这是我的代码 sn-p

    var salt = crypto.randomBytes(128).toString('base64');
    var iterations = 10;
    var keylen = 20;
    crypto.pbkdf2(args.password, salt, iterations, keylen, function(succes, bcryptedPassword) {
                        console.log(bcryptedPassword.toString());
                        //Do actions here
    
                    });

    请检查是否对您有帮助

    【讨论】:

    • 你需要指定一个摘要作为crypto.pbkdf2的第5个参数,例如'sha256'
    【解决方案3】:

    以下语法来自(已废弃?)bcrypt-nodejs 模块1

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

    您参考 bcrypt 模块 2 的文档。

    确保您使用的是正确的模块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2014-05-26
      相关资源
      最近更新 更多