【问题标题】:hashing password in meanjsmeanjs中的哈希密码
【发布时间】:2015-07-08 12:49:15
【问题描述】:

我正在阅读meanjs的源代码,我的问题是带有代码的hashPassword方法:

UserSchema.methods.hashPassword = function(password) {
   if (this.salt && password) {
        return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
    } else {
        return password;
    }
};

这里我不明白为什么它返回密码,以防 this.salt && 密码为假?据我了解,这是一个问题,也许它应该停止保存用户,对吧?

【问题讨论】:

  • 这在我看来确实是一个错误的实现。如果盐初始化不正确,我希望它会触发错误。正如它所写的那样,您能做的最好的事情就是在哈希之前和之后检查===。用于密码保护的服务器端模块会如此简洁,这也让我很困扰。
  • 在下面查看我的答案。仅将这一段代码作为上下文,实现看起来确实有问题,但从整体上看,并非如此。

标签: angularjs hash passwords meanjs


【解决方案1】:

在 hashPassword 函数定义之前,你应该看到这个块:

    /**
     * Hook a pre save method to hash the password
     */
    UserSchema.pre('save', function(next) {
      if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
      }

      next();
    });

如您所见,在调用 hashPassword 之前生成了一个盐。如果您正确使用 meanjs,则永远不会返回纯密码。如果由于任何原因未定义 salt,它不会抛出错误,而是继续并以纯文本形式保存密码。

【讨论】:

    【解决方案2】:

    我对这个方法有一些问题,把它改成这个

    if (this.password && this.password.length > 6) {
        if (!this.salt || this.salt.length === 0) {
            this.salt = crypto.randomBytes(16).toString('base64');
            this.password = this.hashPassword(this.password);
        }
    }
    

    错误是,如果您在初始保存后再次尝试保存用户,您将无法使用该用户详细信息登录。 它会使用盐来加密已经加密的密码会发生什么,这在我看来是错误的。

    因此,处理该问题的两种选择之一是在调用 save 之前始终将用户密码设置为空字符串,或者执行我所做的或类似的事情。

    【讨论】:

      猜你喜欢
      • 2012-07-07
      • 1970-01-01
      • 2023-04-08
      • 2020-04-27
      • 2012-07-09
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      相关资源
      最近更新 更多