gpt4 book ai didi

php - 将 bcrypt 密码哈希从 PHP 迁移到 Python - ValueError : Invalid hashed_password salt

转载 作者:行者123 更新时间:2023-11-30 22:05:54 25 4
gpt4 key购买 nike

我有一个 PHP7 应用程序,它可以像这样对用户密码进行哈希处理

$hash = password_hash($password, PASSWORD_BCRYPT);

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

$2y$10$aazE9OUKZlOQiM6axwxU/utpOURLQ58pluqtFZkkGE3R9ShtUxBOm

现在,我有一个 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

最佳答案

2y2atwo 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 年发布的,所以我认为该项目此时已经死亡。

相反,您应该安装 bcrypt project 。虽然它仅支持 2a2b生成哈希值,但它明确 supports normalising 2y hashes to treat them as 2b 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

关于php - 将 bcrypt 密码哈希从 PHP 迁移到 Python - ValueError : Invalid hashed_password salt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52871295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com