DiSTReKT
DiSTReKT

Reputation: 3

Password(+salt) hashing and verifying in PHP and/or NodeJS

I use in php the following code to generate a password hash and a salt.

$salt = password_hash(uniqid(openssl_random_pseudo_bytes(16), TRUE), PASSWORD_BCRYPT);
password_hash($password . $salt, PASSWORD_BCRYPT);

I am using bcryptin NodeJS and want to achieve to verify the password in NodeJS. I save the hash and the password salt in my database and can query this in my NodeJS application.

After a few researching tries, I found this post on SO: Verify password hash in nodejs which was generated in php Now I added the replace part to my code.

My pseudo:

bcrypt.compare(password_from_input + salt_from_db.replace(/^\$2y(.+)$/i, '\$2a$1'), password_from_db.replace(/^\$2y(.+)$/i, '\$2a$1'), function(err, result) {
  console.log(result);
});

And I also want it the other way around. So create a salt and hash in NodeJS and verify in PHP.

I hope you guys can help me out.

Upvotes: 0

Views: 1196

Answers (1)

Gergo Erdosi
Gergo Erdosi

Reputation: 42053

To hash a password in PHP:

$hash = password_hash($password, PASSWORD_BCRYPT);

This generates a hash with $2y$ that you need to store in the database. Use this code to compare the password in Node:

bcrypt.compare(password_from_input, password_from_db.replace(/^\$2y(.+)$/i, '\$2a$1'), function(err, result) {
  console.log(result);
});

To hash a password in Node:

bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(password_from_input, salt, function(err, hash) {
        hash = hash.replace(/^\$2a(.+)$/i, '\$2y$1');
        //Insert into database
    });
});

This generates a hash with $2a$. The example above replaces it with $2y$, so comparing will be easier in PHP.

To compare a password in PHP:

if (password_verify($password_from_input, $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

Upvotes: 3

Related Questions