为什么 bcryptjs compare 给出空值,即使使用的哈希生成了一个?

问题描述

出于身份验证的目的,当我尝试比较相同字符串的密码时,我将哈希密码存储在 MongoDB 中,bcryptjs 抛出一个空值。

database image

它以二进制形式存储字符串'123'的散列密码。 这是我的生成代码

import bcrypt
salt = bcrypt.gensalt()    
password = bcrypt.hashpw(request.form['password'].encode('utf-8'),salt)

当我尝试将其与用户输入的密码“123”进行比较时,我得到一个空值。

123 $2b$12$URN6pyD4SsOgIXALvr.jIuy2hvxlxva.ioamDNtMhAwvWb9/nLdhO null

这是我的 nodejs 代码和 bcryptjs,用于将用户密码与散列数据库密码进行比较

userSchema.methods.comparePassword = function (passw,cb) {
    var user = this;
    console.log((passw === user.password) ? 'passwords match' : 'passwords dont match' );
    console.log(passw +" "+ user.password )
    bcrypt.compare(passw,user.password,function (err,isMatch) {
        console.log(passw +" "+ user.password +" " +isMatch )
        if(err) {
            return cb(err)
        }
        cb(null,isMatch)
    })
}

即使我输入了相同的字符串“123”,我也得到了一个空值如果我尝试使用这个在线 bcryptchecker 网站 https://bcryptgenerator.com/ 进行检查,我会得到一个匹配项。我到底做错了什么?有人能指出我的错误吗?

解决方法

我认为您在向“bcrypt.compare”方法发送数据时犯了错误。您应该进行更改:

Task task = new Task()    //all use default values

Task task = new Task(name)    //use default values for other fileds

Task task = new Task(name,description)    //the order matters,otherwise you need to explicitlty specify the filed,like following

Task task = new Task(mIsDone = true,mName = "Sam")

有关详细信息,请查看 this