Salt and hash password using bcrypt in Node.js code is given below:
const password = "admin12345678";
const salt = await bcrypt.genSalt();
const passwordHash = await bcrypt.hash(password, salt);
passwordHash is stored in the database.
Do I need to save the salt to the database, for checking comparison in PHP? Is it secure though?
Comparison code in Node.js is as follows.
const password = "admin12345678";
let passwordHash = '$2y$10$jRSNwj.vWLCT/chY4mCTvOuCqOv5PsmVgvektqRQW5BdbMXmZQyZi' // Generated above
if (await bcrypt.compare(password, passwordHash)) { // This works fine_
res.send('LoggedIn');
} else {
res.send('Not Valid User!');
}
PHP equivalent code to generate password hash is given below.
$password = 'admin12345678';
echo $hashed_password = password_hash($password, PASSWORD_BCRYPT);
Output:
$2y$10$0/umkIdTD0PePbtJAP/Z5u7qxOgz8wTn9ZYa5srNqDcLyqp3F7MEC
Node.js compare hash password generated by PHP
const password = "admin12345678";
let passwordHash = '$2y$10$0/umkIdTD0PePbtJAP/Z5u7qxOgz8wTn9ZYa5srNqDcLyqp3F7MEC' // Generated by PHP
if (await bcrypt.compare(password, passwordHash)) { // This failed :(
res.send('LoggedIn');
} else {
res.send('Not Valid User!');
}
When I compare the hashed password generated by PHP in Node.js it doesn’t work. I need to work the hash password generated by PHP to get compared on Node.js and vice versa.