security.py 728 B

12345678910111213141516171819202122
  1. import bcrypt
  2. def verify_password(plain_password: str, hashed_password: str) -> bool:
  3. """验证密码(哈希非 bcrypt 或损坏时返回 False,避免抛错)"""
  4. if not plain_password or not hashed_password:
  5. return False
  6. hp = hashed_password if isinstance(hashed_password, str) else str(hashed_password)
  7. if not hp.startswith("$2"):
  8. return False
  9. try:
  10. return bcrypt.checkpw(
  11. plain_password.encode("utf-8"),
  12. hp.encode("utf-8"),
  13. )
  14. except (ValueError, TypeError):
  15. return False
  16. def get_password_hash(password: str) -> str:
  17. """生成密码哈希"""
  18. return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')