validation在php中生成的nodejs中的密码哈希值

我的php代码使用password_hash生成一个哈希,我将其存储在数据库中。 以下是PHP代码:

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

我想validation/检查在nodejs这个散列的密码。

我看到很多节点模块(bcrypt,phpass,node-bcrypt),但都是假的。 下面是在PHP中生成的示例哈希,我试图在nodejs中validation。

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

(这里的秘密是真实的密码)

我目前的解决方法是通过节点调用一个PHP脚本来validation(对于任何需要解决方法的人)

 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 }); 

这是一个黑客,并不是一个很好的答案这个问题。 有没有一种方法来validation在nodejs的密码,而不使用这样的解决方法?

将哈希密码中的$ 2y $replace为$ 2a $,然后bcrypt.compare会给你正确的结果。

 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); }); 

在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); }); 

我知道这已经得到了答复,但从评论中看来,需要更多的细节。

由php的password_hash()函数产生的Bcrypt哈希分裂如下:

$2y$ 08$ 9TTThrthZhTOcoHELRjuN. 3mJd2iKYIeNlV/CYJUWWRnDfRRw6fD2

 | | | | | | Salt Hashed Password | | | Algorithm options (cost, in this case) | Algorithm type 

从这里的其他答案看来,虽然Bcrypt的PHP和Node版本使用不同的algorithm,但是散列输出中唯一的区别是前缀。 所以,所需要的就是@Sudesh提到的将$2y$换成$2a$和Bob的叔叔。

来源

http://php.net/manual/en/faq.passwords.php

在Node.js中$ 2y bcrypt哈希

比较PHP和NodeJS之间的BCrypt哈希