如何在 NodeJS 应用程序中验证 PHP 散列密码

How to verify a PHP hashed password in a NodeJS app

我在 PHP 上的应用程序 运行 多年来,我使用 PHP 5.5 推荐的 password hashing API 来存储我的用户密码。例如:

$password = password_hash("my password", PASSWORD_DEFAULT);

因此,我的数据库中充满了这样的密码:

y$sjzYz7g/kVxpJUynC/...........pjKPh0z1QuU.Mlt7TVAiPW

现在我将我的应用程序移到 NodeJS 12.3.0 上的 运行 而不是 PHP 我现在使用 bcrypt library 像这样:

const saltRounds = 10;
const password = await bcrypt.hash("my password", saltRounds);

相同的密码散列如下:

b$SYZH5Mj4Dy8dkKyRv1O/.........XNGPVBe8nPJjpnEjPZxx.

我认为使用的算法、盐和圆都在弦内,因此 t运行 位置将是无缝的。但是,当我尝试验证 PHP 存储的密码时,正确的密码验证失败:

// result === false
const result = await bcrypt.compare("my password", phpStoredHash);

我真的希望我不必强迫所有用户重设密码。如何验证存储在我的 NodeJS 应用程序中的密码 PHP?

这没有任何盐轮,PASSWORD_DEFAULT 使用 BCRYPT

$password = password_hash("my password", PASSWORD_DEFAULT);

尝试进行以下更改:

$password = password_hash("my password", PASSWORD_BCRYPT);

改用bcryptjs包。它可以正确比较 php 生成的哈希值。

const bcrypt = require('bcryptjs')

const hashPHP = "y$Lsn001yN38WssfQmJ5hM5.Ywa3AKB76YD/zUC9QNS5BPRr9QMWOTa"
console.log(bcrypt.compareSync("my password", hashPHP));  // outputs: true