即使两个密码字符串完全匹配,为什么我从 bcrypt compare 中得到 isMatch null?

问题描述

我正在尝试根据密码对用户进行身份验证。我正在使用 bcrypt compare 来比较用户请求的密码和 mongodb 中的一个,但即使两个密码完全匹配我也得到空值,这是我正在尝试的代码

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

我得到如下控制台输出

sh37xb sh37xb null

分别是用户输入的密码、该用户数据库中的密码以及 isMatch 值 这是 null 而不是它必须是相反的,因为两个密码完全匹配。 当我用三元条件检查这个密码时,它说“密码匹配”但不是 bcrypt.compare。我究竟做错了什么?谁能帮我指出我的错误??

解决方法

当用户注册时,您保存的是它的散列版本,而不是实际文本。

const password = req.body.password
// This hasedPassword will be saved to database
const salt = await bcrypt.genSalt(10)
const hashedPassword = await bcrypt.hash(password,salt)

当用户尝试登录时,bcrypt 将用户输入的密码与 hashedPassword 进行比较

const saveHashedPassword = user.password
const enteredPassword = passw
bcrypt.compare(enteredPassword,saveHashedPassword,function(err,result) {
    // Do your logic
    if(err) {
            return cb(err)
    }
    cb(null,isMatch)
})

,

bcrypt.compare 的第二个参数应该是散列,而不是纯文本字符串。

Bcrypt compare 不会将纯文本密码与另一个纯文本密码进行比较。它计算纯文本密码的哈希值,并将其与您作为第二个参数提供的早期哈希值进行比较 查看哈希值是否匹配。

使用 bcrypt compare 的典型原因是它比字符串比较更安全。为此,密码数据库需要包含散列密码,而不是纯文本密码。纯文本密码数据库很容易被窃取。散列字符串的数据库不太有用。

npm page for bcrypt 给出了这个例子:

To check a password:
// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword,hash,result) {
    // result == true
});
bcrypt.compare(someOtherPlaintextPassword,result) {
    // result == false
});