How to verify a PHP hashed password in a NodeJS app

喜夏-厌秋 提交于 2019-12-11 15:22:18

问题


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. 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:

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:

// 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?


回答1:


Use bcryptjs package instead. It can compare php generated hashes correctly.

const bcrypt = require('bcryptjs')

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



回答2:


This does not have any salt rounds,PASSWORD_DEFAULT uses BCRYPT

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

Try to make following change :

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


来源:https://stackoverflow.com/questions/58762951/how-to-verify-a-php-hashed-password-in-a-nodejs-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!