密码(+盐)哈希和验证PHP和/或NodeJS


Password(+salt) hashing and verifying in PHP and/or NodeJS

我在php中使用以下代码来生成密码哈希和盐。

$salt = password_hash(uniqid(openssl_random_pseudo_bytes(16), TRUE), PASSWORD_BCRYPT);
password_hash($password . $salt, PASSWORD_BCRYPT);

我在 NodeJS 中使用bcrypt,并希望在 NodeJS 中验证密码。我将哈希和密码盐保存在数据库中,并可以在我的 NodeJS 应用程序中查询它。

经过几次研究尝试,我在SO上找到了这篇文章:验证在 php 中生成的 nodejs 中的密码哈希现在,我将替换部分添加到我的代码中。

我的伪:

bcrypt.compare(password_from_input + salt_from_db.replace(/^'$2y(.+)$/i, ''$2a$1'), password_from_db.replace(/^'$2y(.+)$/i, ''$2a$1'), function(err, result) {
  console.log(result);
});

我也希望反过来。因此,在 NodeJS 中创建盐和哈希并在 PHP 中进行验证。

我希望你们能帮助我。

要在 PHP 中对密码进行哈希处理:

$hash = password_hash($password, PASSWORD_BCRYPT);

这将生成一个哈希,其中包含您需要存储在数据库中的$2y$。使用此代码比较 Node 中的密码:

bcrypt.compare(password_from_input, password_from_db.replace(/^'$2y(.+)$/i, ''$2a$1'), function(err, result) {
  console.log(result);
});

要在 Node 中对密码进行哈希处理:

bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(password_from_input, salt, function(err, hash) {
        hash = hash.replace(/^'$2a(.+)$/i, ''$2y$1');
        //Insert into database
    });
});

这将生成一个带有 $2a$ 的哈希。上面的例子用$2y$替换了它,所以在PHP中比较会更容易。

要比较 PHP 中的密码:

if (password_verify($password_from_input, $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}