20 lines
737 B
Python
20 lines
737 B
Python
"""认证相关的密码散列与兼容迁移工具。"""
|
|
import hashlib
|
|
import hmac
|
|
|
|
import bcrypt
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
"""使用 bcrypt 保存密码,避免快速散列被离线撞库。"""
|
|
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
|
|
|
|
|
def verify_password(password: str, stored_hash: str) -> tuple[bool, bool]:
|
|
"""返回 (密码是否正确, 是否需要将旧 SHA-256 散列升级为 bcrypt)。"""
|
|
if stored_hash.startswith("$2"):
|
|
return bcrypt.checkpw(password.encode("utf-8"), stored_hash.encode("utf-8")), False
|
|
|
|
legacy_hash = hashlib.sha256(password.encode("utf-8")).hexdigest()
|
|
return hmac.compare_digest(legacy_hash, stored_hash), True
|