Question
Why am I getting false results when comparing passwords hashed with bcrypt?
const bcrypt = require('bcrypt');
const password = 'myPassword';
const hashedPassword = await bcrypt.hash(password, 10);
const isMatch = await bcrypt.compare('wrongPassword', hashedPassword);
console.log(isMatch); // Always false
Answer
When using bcrypt to hash passwords, it’s vital to ensure that you're comparing the original password with the correct hashed version. If the comparison always returns false, it's likely due to mismatches in password formats, incorrect hashed values, or issues in the implementation process.
const bcrypt = require('bcrypt');
const password = 'myPassword';
const hashedPassword = await bcrypt.hash(password, 10);
// Correct comparison
const isMatch = await bcrypt.compare(password, hashedPassword);
console.log(isMatch); // Should return true
Causes
- The plain password being compared is not the same as the original when hashed.
- The hashed password has been altered or improperly stored.
- Different salts are inadvertently used for hashing and comparison, which bcrypt automatically handles but requires consistent input.
Solutions
- Ensure the password you're comparing is the one originally hashed.
- Verify that the stored hash hasn’t been modified or corrupted.
- Utilize bcrypt’s built-in methods correctly, maintaining consistent use of salts.
Common Mistakes
Mistake: Using the wrong password for comparison.
Solution: Always use the original password string that was hashed.
Mistake: Expecting a false return due to mismatched salt without realizing bcrypt handles it.
Solution: Trust bcrypt to manage the salt and focus on input consistency.
Mistake: Overlooking errors during the hashing process.
Solution: Always handle potential errors in your code to ensure robust implementation.
Helpers
- bcrypt
- hashed passwords
- password comparison
- bcrypt comparison issue
- password hashing best practices