Kamixitong/test_password_fix.py

60 lines
1.8 KiB
Python
Raw Normal View History

2025-11-22 20:32:49 +08:00
#!/usr/bin/env python3
"""
测试密码验证修复
用于验证 Werkzeug 版本兼容性问题是否已解决
"""
import sys
import os
# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from werkzeug.security import generate_password_hash, check_password_hash
import hashlib
import hmac
import base64
def test_password_hash():
"""测试密码哈希生成和验证"""
password = "admin123"
# 生成密码哈希
hash1 = generate_password_hash(password)
print(f"生成的密码哈希: {hash1}")
# 测试标准验证
try:
result1 = check_password_hash(hash1, password)
print(f"标准验证结果: {result1}")
except Exception as e:
print(f"标准验证失败: {e}")
result1 = False
# 测试兼容性验证
if not result1 and hash1.startswith('$pbkdf2-sha256$'):
try:
parts = hash1.split('$')
if len(parts) == 5:
iterations = int(parts[2])
salt_str = parts[3]
stored_hash_str = parts[4]
# 解码
salt_bytes = base64.b64decode(salt_str + '==')
stored_hash_bytes = base64.b64decode(stored_hash_str + '==')
# 计算
password_bytes = password.encode('utf-8')
computed_hash_bytes = hashlib.pbkdf2_hmac('sha256', password_bytes, salt_bytes, iterations)
# 比较
result2 = hmac.compare_digest(computed_hash_bytes, stored_hash_bytes)
print(f"兼容性验证结果: {result2}")
except Exception as e:
print(f"兼容性验证失败: {e}")
if __name__ == '__main__':
test_password_hash()