简体   繁体   English

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

[英]How to verify a PHP hashed password in a NodeJS app

My application ran on PHP for years, and I used the recommended password hashing API as of PHP 5.5 to store my users' passwords.我的应用程序在 PHP 上运行多年,我使用自 PHP 5.5 起推荐的密码散列 API来存储我的用户密码。 For instance:例如:

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

As a result, my database is full of passwords such as this:结果,我的数据库充满了这样的密码:

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

Now I am moving my application to run on NodeJS 12.3.0 instead of PHP and I now use the bcrypt library like this:现在我将我的应用程序移动到NodeJS 12.3.0而不是 PHP 上运行,我现在使用bcrypt,如下所示:

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

The same password hashes to something like:相同的密码哈希为:

$2b$10$SYZH5Mj4Dy8dkKyRv1O/.........XNGPVBe8nPJjpnEjPZxx.

I thought that the algo, salt and rounds used were within the string so that the transition would be seamless.我认为使用的算法、盐和轮数都在字符串内,这样过渡就会无缝。 However, when I try to verify a password that had been stored by PHP, the correct password fails verification:但是,当我尝试验证 PHP 存储的密码时,正确的密码验证失败:

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

I really hope I don't have to force all users to reset their passwords.我真的希望我不必强迫所有用户重置他们的密码。 How can I verify the passwords PHP stored in my NodeJS application?如何验证存储在我的NodeJS应用程序中的密码 PHP?

Use bcryptjs package instead.改用 bcryptjs package。 It can compare php generated hashes correctly.它可以正确比较 php 生成的哈希值。

const bcrypt = require('bcryptjs')

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

This does not have any salt rounds,PASSWORD_DEFAULT uses BCRYPT这没有任何盐轮,PASSWORD_DEFAULT 使用 BCRYPT

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

Try to make following change:尝试进行以下更改:

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

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

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