I am working on a login script with Node.js and using bcrpyt to compare password hashes. When using the bcrpyt library, the compare function fails. However when I use the bcrpytjs library, the compare function succeeds. Below is the login function. I've included the hash and password for use is testing.
Password: LHLiiSGd1xLg
Hash: $2y$10$J47x5GEFtmULWem2nh3YvuZaAiZyFZlyTUFV97dAx2.dyb8Yst43y
function login(email, password, callback) {
// Require depedencies
const bcrypt = require("bcrypt")
const mysql = require('mysql');
// Create our mysql connection
const connection = mysql.createConnection({
host: configuration.host,
user: configuration.user,
password: configuration.password,
database: configuration.database
});
// Connect to the database
connection.connect();
// Create the database query
const query = 'SELECT id, firstname, lastname, email, password FROM tblclients WHERE email = ?';
// Query the database
connection.query(query, [ email ], function(err, results) {
// If we have an error
if (err) return callback(err);
// If we have no results
if (results.length === 0) return callback(new WrongUsernameOrPasswordError(email));
// Define the user object
const user = results[0];
console.log('Query: ', results);
// Compare the two hashes
bcrypt.compare(password, user.password.toString(), function(err, isMatch) {
// If the passwords do not match
if (err) return callback(err);
if (!isMatch) return callback('Passwords do not match');
// Return the user
callback(null, {
user_id: user.id.toString(),
nickname: user.firstname + ' ' + user.lastname,
email: user.email
});
});
});
}
I replaced the 2y prefix with 2a and the function now correctly works.
user.password.toString().replace(/^\$2y/, "$2a")