简体   繁体   中英

nodejs - bcrypt: compare hash with password always return not match

i'm trying to use the npm package 'bcrypt' for insert crypted password during signup on my PSQL db and login a user.

The operations that i do:

1) Signup: Insert username and crypted password on my PostgreSQL db

createUser: function(username, password) {
        bcrypt.genSalt(saltCount, function(err, salt) {
            bcrypt.hash(password, salt, function(err, hash) {
                query = "insert query with generated crypt password";
                pool.query(query, (err, res) => {
                    console.log(err, res);
                })
            });
        });
    }

2) Login user: get inserted password and compare with crypted password on PostgreSQL db

login: function(username, password) {
        const query = "select query for get crypt passowrd on db";
        pool.query(query, (err, res) => {
            const dbPsw = res.rows[0].hash_psw; // db password
            bcrypt.compare(password, dbPsw, function(err, result) {
                if (err)
                    console.log(err);
                else if (result)
                    console.log("password match");
                else
                    console.log("not match");
            });
        })
    }

The result of second function is always "not match".

I saw on my PSQL db that the inserted password by the first function is always different event i always insert the same password to be crypted.

So my question is: How can i get always the same crypted password? I'm probably doing something wrong but i follow the guide on npm site.

Thanks for your help.

 query = "insert query with generated crypt password";

That should be query = "insert query with generated hash " because bcrypt.hash() gives a hash as seen in the method parameter : function(err, hash) so this callback receives either an error or a hash

There's an interesting question on how bcrypt compare works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM