繁体   English   中英

验证在PHP中生成的nodejs中的密码哈希

[英]Verify password hash in nodejs which was generated in php

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

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

我想针对/ nodejs中的哈希验证/检查密码。

我看到了很多节点模块(bcrypt,phpass,node-bcrypt),但它们全都给我带来了错误。 以下是在php中生成的示例哈希,我正尝试在nodejs中进行验证。

var hash = '$2y$08$9TTThrthZhTOcoHELRjuN.3mJd2iKYIeNlV/CYJUWWRnDfRRw6fD2';

var bcrypt = require('bcrypt');

bcrypt.compare("secret", hash, function(err, res) {
    console.log(res);
});

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

我当前的解决方法是通过节点调用php脚本进行验证(适用于需要解决方法的任何人)

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

这是一个hack,不是解决此问题的好方法。 有没有一种方法可以验证nodejs中的密码,而无需使用类似的解决方法?

将散列密码中的$ 2y $替换为$ 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

从SO的其他答案看来,虽然Bcrypt的PHP版本和Node版本使用不同的算法,但哈希输出中的唯一区别是前缀。 因此,正如@Sudesh所述,所需要做的就是将$2y$交换为$2a$而Bob是您的叔叔。

资料来源

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

Node.js中的$ 2y bcrypt哈希

比较PHP和NodeJS之间的BCrypt哈希

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM