comparing two same string hashing in bcrypt returns undefined

Issue

I’m trying to hashing two same string and compare them to validate whether the password is correct or not. I’ve used bcrypt package in nodeJS.
When I use bcrypt.compare method, it returns undefined!

Here is my code:

var akbar, akbar2;
  bcrypt.hash('salam', saltRounds, (err, hash) => {
    akbar = hash;
    console.log(akbar);
  });

  bcrypt.hash('salam', saltRounds, (err, hash) => {
    akbar = hash;
  });

  bcrypt.compare(akbar, akbar2, (err, res) => {
    console.log(akbar, akbar2, res);
  });

here is the console result:

undefined undefined undefined
$2b$10$6dxYYYc2Ud3dVVeWU9GcOe6v9l8FT7GR5gNC6Pt0Xc1N.Si1R.EIC

Solution

Because bcrypt.hash is the async function, when you compare it both bcrypt.hash may not finish yet, therefore it prints undefined for akbar and akbar2. You also cannot compare akbar and akbar2 since it will always return false. You should only compare either ‘salam’ with akbar or ‘salam’ with akbar2.

bcrypt.hash('salam', 10, (err, hash) => {
    const akbar = hash;

    bcrypt.compare('salam', akbar, (err, isMatch) => {
        console.log(isMatch);
    });
});

Answered By – dnp1204

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published