cmcd cmcd - 2 months ago 8
Node.js Question

Node bcrypt's compare always returns false

I am stumped trying to get my passwords to successfully compare with bcrypt using node. Maybe I missed something, but on account creation, I do the following within the signup method (with some code abbreviated):

bcrypt.genSalt(10, function(err, salt) {
if(err) {

}
bcrypt.hash(user.Password, salt, function(err, hash) {
console.log('hashing and saving');
db.query(db insert code, function (error, rows, fields) {
if(error) {
console.log(error);
res.setHeader('500', { 'Content-Type': 'x-application/json'});
res.send({UserId: 0, ErrorMessage: 'Something terrible happened.'});
} else {
console.log('User created : ' + rows.insertId);
res.setHeader('200', { 'Content-Type': 'x-application/json'});
res.send({UserId: rows.insertId});
}
});
});
});

return next();


This all works fine. My db has the encrypted password. But when a user signs in, I cannot get a successful result from bcrypt.compare:

db.query(get account code, function(error, rows, fields) {
if(rows.length == 1) {
bcrypt.compare(request.params.password, rows[0].Password, function(err,res) {
if(err) { console.log(err.toString()); }
if(res == true)
{
response.setHeader('200', { 'Content-Type': 'x-application/json' });
response.send({result: true});
} else {
response.setHeader('401', { 'Content-Type': 'x-application/json' });
console.log('invalid password');
response.send({result:false});
}
});
}
});

return next();


And I always end up with invalid password. Do I need to take the cleartext password and re-encrypt it before comparing to what I pull out of the database?

Answer

you can skip doing bcrypt.genSalt and use bcrypt.hash(password, 10, function(err, hash) {..});

your compare function seems good to me.

this is working fine for me:

var bcrypt = require('bcrypt');

bcrypt.hash('mypassword', 10, function(err, hash) {
    if (err) { throw (err); }

    bcrypt.compare('mypassword', hash, function(err, result) {
        if (err) { throw (err); }
        console.log(result);
    });
});