![](/img/trans.png)
[英]AngularJS: Why am I getting NaN for this even though they display correctly?
[英]Why am I getting isMatch null from bcrypt compare even though two password string matches perfectly?
我正在尝试根据密码对用户进行身份验证。 我正在使用 bcrypt compare 来比较用户请求的密码和 mongodb 中的一个密码,但即使两个密码完全匹配,我也得到 null 值,这是我正在尝试的代码
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)
})
}
我得到控制台 output 如下
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 不会将纯文本密码与另一个纯文本密码进行比较。 它计算纯文本密码的 hash 并将其与您作为第二个参数提供的较早的 hash 进行比较,以查看哈希是否匹配。
使用 bcrypt compare 的典型原因是它比字符串比较更安全。 为此,密码数据库需要包含散列密码,而不是纯文本密码。 纯文本密码数据库很容易被窃取。 散列字符串的数据库不太有用。
bcrypt 的 npm 页面给出了这个例子:
To check a password:
// Load hash from your password DB.
bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
// result == true
});
bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) {
// result == false
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.