Nodejs: 在bcrypt中,比较密码哈希时返回false

3

我在这里使用bcryptjs库来加密我的密码,当我将其插入到数据库中时,它可以正常工作,但每次比较我在数据库中插入的相同密码时,它都会返回false。以下是我的代码,请告诉我哪里出错了。

这段代码用于将哈希密码插入数据库中,它可以完美地工作。

     bcrypt.hash(insertData.Password, 10, function(err, hash) {
            // Store hash in your password DB.
            console.log('hash' , hash)
            insertData.Password = hash;

            insertIntoDB(table,insertData,function(result){
                if(result && result.length > 0){
                        res.json({
                            "status":"1",
                            "result":result[0]._id
                        });
                }
            });
     });

这里是比较密码的代码,但它总是返回false。

var actualPass = results[0].Password //Store in DB password
bcrypt.hash(UserInputPassword, 10, function(err, hash) {
        console.log('hash' , hash)

        bcrypt.compare(actualPass, hash, function(err, response) {
            if(err){
                 console.log("err",err)
             }else{
                 console.log("response",response)                               
             }

        });
 });

你尝试过将actualPass与数据库中的哈希值(例如insertData.Password)进行compare()比较,而不是与新生成的哈希值进行比较吗? - mscdex
是的,我尝试过了,这是我的代码,你可以检查一下。但我不知道它是如何工作的。 - Pratik Parekh
1个回答

10

当你使用compare()函数时,需要将明文值作为第一个参数传递,将来自数据库的哈希值作为第二个参数传递。例如:

当你使用compare()时,需要将明文值作为第一个参数传入,将来自数据库的哈希值作为第二个参数传入。例如:

var hashFromDB = '$2a$10$foo';
var plainPassFromUser = 'mypassword';

bcrypt.compare(plainPassFromUser, hashFromDB, function(err, matches) {
  if (err)
    console.log('Error while checking password');
  else if (matches)
    console.log('The password matches!');
  else
    console.log('The password does NOT match!');
});

在进行数据库插入时,您只需要使用bcrypt.hash()一次而不需要在compare()之前再次使用它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接