PHP哈希的密码在Python验证时报错,求用变量指定2b哈希的方法
解决PHP哈希密码在Python中验证的问题
错误原因分析
cursor.fetchall()返回的是二维列表(比如[(b'$2y$10...',)]),不是单个哈希值,直接传入bcrypt.checkpw会触发类型错误。- PHP生成的bcrypt哈希前缀是
$2y$,Python的bcrypt库仅识别$2b$前缀,需要替换后才能验证。
修正后的代码
import mysql.connector import bcrypt # 连接数据库 mydb = mysql.connector.connect( host="localhost", user="root", password="", port="3307", database="registration" ) cursor = mydb.cursor() # 查询指定用户的哈希密码 cursor.execute("select password from users where username = 'test'") result = cursor.fetchall() # 处理查询结果并验证密码 if result: # 取出查询结果中的哈希值,确保为字节类型 php_hash = result[0][0].encode('utf-8') if isinstance(result[0][0], str) else result[0][0] # 将PHP的$2y$前缀替换为Python bcrypt兼容的$2b$ compatible_hash = php_hash.replace(b'$2y$', b'$2b$') password = "test" if bcrypt.checkpw(password.encode('utf8'), compatible_hash): print("密码验证成功") else: print("密码验证失败") else: print("未找到该用户") # 关闭数据库连接 cursor.close() mydb.close()
关键处理点
- 提取有效哈希值:通过
result[0][0]从查询结果中取出单个哈希值,避免传入列表导致类型错误。 - 前缀兼容处理:PHP的
$2y$与Python的$2b$是等价的bcrypt哈希变体,替换后才能被Python的bcrypt库正确解析。 - 字节类型统一:确保待验证密码和哈希值都转换为字节类型,符合
bcrypt.checkpw的参数要求。
内容的提问来源于stack exchange,提问作者Walter Kindblad
相关产品推荐
相关产品推荐

