Files
shanxia2.0/backend/app/core/security.py
T
2026-05-12 16:35:07 +08:00

23 lines
728 B
Python

import bcrypt
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""验证密码(哈希非 bcrypt 或损坏时返回 False,避免抛错)"""
if not plain_password or not hashed_password:
return False
hp = hashed_password if isinstance(hashed_password, str) else str(hashed_password)
if not hp.startswith("$2"):
return False
try:
return bcrypt.checkpw(
plain_password.encode("utf-8"),
hp.encode("utf-8"),
)
except (ValueError, TypeError):
return False
def get_password_hash(password: str) -> str:
"""生成密码哈希"""
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')