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

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

本文介绍了验证在PHP中生成的nodejs中的密码哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的php代码使用password_hash生成哈希,并将其存储在数据库中.下面是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));

我想根据nodejs中的哈希值验证/检查密码.

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

我看到了很多节点模块(bcrypt,phpass,node-bcrypt),但是它们全都给我带来了错误.下面是在php中生成的示例哈希,我正尝试在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)

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

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

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

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?

推荐答案

用$ 2a $替换哈希密码中的$ 2y $,然后bcrypt.compare应该会给您正确的结果.

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

在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中生成的nodejs中的密码哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 03:25