Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify password hash in nodejs which was generated in php

My php code generates a hash using password_hash which I store in a database. Below is the PHP code:

$hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost)); 

I would like to verify / check the password against this hash in nodejs.

I saw lot of node modules (bcrypt, phpass, node-bcrypt), but all of them give me false. Below is sample hash generated in php and which I m trying to verify in nodejs.

var hash = '$2y$08$9TTThrthZhTOcoHELRjuN.3mJd2iKYIeNlV/CYJUWWRnDfRRw6fD2';  var bcrypt = require('bcrypt');  bcrypt.compare("secret", hash, function(err, res) {     console.log(res); }); 

(Here secret is real password)

My current workaround is to call a php script via node to verify (for anybody who needs a workaround)

var exec = require('child_process').exec; var cmd = 'php verify.php password encryped_pasword'; exec(cmd, function (error, stdout, stderr) {   // output is in stdout   console.log(stdout);  //If stdout has 1 it satisfies else false }); 

This is a hack and not a good answer to this problem. Is there a way to verify the password in nodejs without using a workaround like this?

like image 844
Sudesh Avatar asked Apr 11 '14 14:04

Sudesh


People also ask

How is a hashed password verified?

You will need to verify the user passwords to see if they match the passwords stored in the database. To do this, we call check() on the Hash façade. The check() method verifies if the plain-text string entered by the user matches the given hash.

What is PHP password hash?

password_hash() creates a new password hash using a strong one-way hashing algorithm. The following algorithms are currently supported: PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5. 0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP.


1 Answers

Replace $2y$ in the hashed password with $2a$,then bcrypt.compare should give you correct result.

var hash = '$2y$08$9TTThrthZhTOcoHELRjuN.3mJd2iKYIeNlV/CYJUWWRnDfRRw6fD2'; var bcrypt = require('bcrypt'); hash = hash.replace(/^\$2y(.+)$/i, '$2a$1'); bcrypt.compare("secret", hash, function(err, res) {     console.log(res); }); 

on ES6:

import bcrypt from 'bcrypt'; let hash = '$2y$08$9TTThrthZhTOcoHELRjuN.3mJd2iKYIeNlV/CYJUWWRnDfRRw6fD2'; hash = hash.replace(/^\$2y(.+)$/i, '$2a$1'); bcrypt.compare('secret', hash, function(err, res) {     console.log(res); }); 
like image 163
Calvin Liu Avatar answered Sep 23 '22 07:09

Calvin Liu