我的 php 代码使用我存储在数据库中的 password_hash
生成哈希。下面是PHP代码:
$hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost));
我想在 nodejs 中根据这个哈希验证/检查密码。
我看到了很多 Node 模块(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);
});
(这里的 secret 是真实密码)
我目前的解决方法是通过 Node 调用 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 - 验证在 php 中生成的 nodejs 中的密码哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23015043/