代码之家  ›  专栏  ›  技术社区  ›  Tim__

bcrypt节点。js(自动生成salt和hash)

  •  2
  • Tim__  · 技术社区  · 7 年前

    在将用户密码存储到数据库之前,我使用以下代码对其进行散列(希望是salt)。

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

    基于文件( https://www.npmjs.com/package/bcrypt )对于bcrypt,我希望得到以下代码

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

    为什么有两个“null”参数?它们是干什么的?

    3 回复  |  直到 7 年前
        1
  •  2
  •   Matt Goodrich    7 年前

    两者之间有区别 bcrypt bcrypt-nodejs 以下代码来自他们在npmjs.com上的文档。

    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-[必需]-用于散列密码的salt。
    • 进度-在哈希计算期间调用的回调,以表示进度
        2
  •  1
  •   Seena V P    7 年前

    我使用加密库进行哈希运算,效果很好。这是我的代码片段

    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
    
                    });

        3
  •  0
  •   Fabian    7 年前

    1

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

    请参阅bcrypt模块的文档 2