Peter Boomsma Peter Boomsma - 3 months ago 11
Node.js Question

Passport bcrypt password is different than password from db

In my

local-register
I store my user data in the database. To hash the password I use bcrypt:

console.log(password);
password = bcrypt.hashSync(password);
console.log(password);


If I sign up a user with the password
stackoverflow
the password looks like this:

stackoverflow
$2a$10$uoJH1Wo9b7SQploRptfODe1Q2kRC3skQoUNOIhAmHg2AWykWQwGvW


When I log in a user
stackoverflow@stackoverflow.com
with the password
stackoverflow


var hashedpassword = bcrypt.hashSync(password);
console.log(password);
console.log(hashedpassword);

stackoverflow
$2a$10$aq869JEMWBQ8vCfXfuRvlOPdUvq.UhTz4Ge.kB3n7wSyvhjBsm8r2


So even though I use the same bcrypt module the hash is different every time I log in.

Answer

I don't understand the inner workings of bcrypt, but the hash may look different for the same string each time because the salt is generated as part of the hashing. Thus, you can't do:

stored = hash(old);
guess = hash(guess);
valid = stored == guess;

Instead you have to use the compare method, as in:

/* password is *not* hashed! */
bcrypt.compare(password, usersHashedPassword, cb);
Comments