5

I'm developing a Node.js application that needs to log in using the same database information from a Laravel aplication.

I've read about BCrypt and trying to use it to make a comparison of the hashed password it generates with the Laravel one stored in the database.

So, by the documentation of BCrypt, I need to do something like that:

var salt = bcrypt.genSaltSync(saltRounds);
var hash = bcrypt.hashSync(myPlaintextPassword, salt);

But I have no idead on how to use the exact same salt from Laravel to hash my password. I need to use the APP_KEY to do this?

Bruno Albuquerque
  • 597
  • 1
  • 7
  • 21

2 Answers2

18

I fond the answer here. It's way easier than I thought.

var hash = '$2y$08$9TTThrthZhTOcoHELRjuN.3mJd2iKYIeNlV/CYJUWWRnDfRRw6fD2';
var bcrypt = require('bcrypt');
hash = hash.replace(/^\$2y(.+)$/i, '$2a$1');
bcrypt.compare("secret", hash, function(err, res) {
    console.log(res);
});
Bruno Albuquerque
  • 597
  • 1
  • 7
  • 21
2

To my understanding, the salt is stored as part of the hash.

So why not just compare a plain text against the stored hash.

Try the following (from bcrypt docs) :

bcrypt.compare(myPlaintextPassword, hash, function(err, res) {
    // res == true
});

hash would be the users password hash value in the Laravel database.

for example :

var pass_hash = '$2y$12$Z3Dk1YAzNsdXxq8EKNQxluqGglI6dvncfJxDj0mZHh7zceX2XoX/W'
var pass_string = '1234'
bcrypt.compare(pass_string, pass_hash,(err,valid)=>{
 if(valid){console.log("valid password match")}
 else{console.log("wrong credentials")}
});
EMX
  • 6,066
  • 1
  • 25
  • 32
  • It doesn't work. The `compare`always return "wrong credentials". – Bruno Albuquerque Jun 19 '19 at 14:49
  • Are you sure you have the valid match for the specific hash? – EMX Jun 19 '19 at 15:24
  • Yes. I've made the password using **Hash::make** from Laravel and I know for sure what the password without hash is. – Bruno Albuquerque Jun 19 '19 at 16:21
  • if you console.log the pass_hash before comparing does it show the one from the database? (just making sure you are not comparing something wrong or an undefined value)... If you test my example, hard-coding the pass_hash and the pass_string, does it work? – EMX Jun 19 '19 at 17:43