将bcrypt password hash从PHP迁移到Python ValueError:hashed_password s无效

2024-06-02 05:51:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个PHP7应用程序,可以像这样散列用户的密码

$hash = password_hash($password, PASSWORD_BCRYPT);

例如,如果我将test1234传递给它,我得到:

^{pr2}$

现在,我有一个Python应用程序,它也需要更新用户的密码。它使用的是这样的:

import bcrypt

hash = bcrypt.hashpw(password, bcrypt.gensalt())

例如,相同的密码test1234散列为:

$2a$12$vsI9Vf9gWj/Au3McYradxuozyZychmlfqoCJcSacDWuMzUDVpv33m

如您所见,PHP生成了$2y,而Python生成了$2a-因此它们是哈希的不同版本。在

现在,如果我尝试在PHP中验证Python和PHP散列,如下所示:

$result = password_verify($password, $hash);

两种情况下我都有true。但是,如果我尝试在Python端验证这两种方法:

bcrypt.checkpw(password, hash)

它只适用于当我传递Python生成的散列时。如果我传递在PHP中生成的散列,我得到:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: Invalid hashed_password salt

我的问题是:我有什么遗漏吗?在

bcrypt模块由我使用pip安装的py-bcrypt项目0.4版提供:

pip3 install py-bcrypt

Tags: 用户pyimport应用程序密码passwordhashphp
1条回答
网友
1楼 · 发布于 2024-06-02 05:51:07

2y和{}是two different versions of the bcrypt algorithm。正如维基百科所说,2y仅对PHP特定:

In June 2011, a bug was discovered in crypt_blowfish, a PHP implementation of BCrypt. [...] They also suggested the idea of having crypt_blowfish emit $2y$ for hashes generated by the fixed algorithm.

Nobody else, including canonical OpenBSD, adopted the idea of 2x/2y. This version marker change was limited to crypt_blowfish.

py-bcrypt模块落后于时代,因为它只支持2a版本!截至2014年2月,2b版是当前版本(修正了一个超过255个字符的密码散列错误)。目前的0.4版本是在2013年发布的,所以我认为这个项目现在已经死了。在

相反,您应该安装^{} project。虽然它只支持2a2b来生成哈希,但它显式地supports normalising ^{} hashes to treat them as ^{} hashes,因此我可以使用该项目验证2y哈希:

>>> import bcrypt
>>> bcrypt.__version__
'3.1.4'
>>> hash = b'$2y$10$aazE9OUKZlOQiM6axwxU/utpOURLQ58pluqtFZkkGE3R9ShtUxBOm'
>>> bcrypt.checkpw(b'test1234', b'$2y$10$aazE9OUKZlOQiM6axwxU/utpOURLQ58pluqtFZkkGE3R9ShtUxBOm')
True

相关问题 更多 >