Nodejs : in bcrypt it returns false at compare password hash

 ̄綄美尐妖づ 提交于 2021-01-27 12:26:18

问题


Here I use bcryptjs library to encrypt my password, Its works fine when i insert into db but its returns false every time to compare same password which i insert in DB. Here is my code.. Please tell me where i am wrong.

This code for inserting hash password in DB , It works perfect

     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
                        });
                }
            });
     });

And Here is code for compare password but it always returns 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)                               
             }

        });
 });

回答1:


When you compare(), you need to pass in the plaintext value as the first argument and the hash from your database as the second argument. For example:

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!');
});

You also don't need to bcrypt.hash() a second time before compare(). Just once when you're inserting into the database.



来源:https://stackoverflow.com/questions/24583608/nodejs-in-bcrypt-it-returns-false-at-compare-password-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!