我正在使用Node.js处理登录脚本,并使用bcrpyt比较密码哈希。使用bcrpyt库时,比较功能将失败。但是,当我使用bcrpytjs库时,compare函数成功。下面是登录功能。我已包含用于测试的哈希和密码。
密码:LHLiiSGd1xLg
哈希:$ 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
});
});
});
}
我用2a替换了2y前缀,该函数现在可以正常使用。
user.password.toString().replace(/^\$2y/, "$2a")