rewrited logic structure

This commit is contained in:
2026-09-09 16:43:57 +08:00
parent 1947a27514
commit ac6d2cf3b4
20 changed files with 1717 additions and 1496 deletions

26
group_system/security.py Normal file
View File

@@ -0,0 +1,26 @@
"""密码散列与校验。"""
from __future__ import annotations
import hashlib
import hmac
import secrets
def hash_password(password: str, salt: bytes | None = None) -> str:
salt = salt or secrets.token_bytes(16)
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 180_000)
return salt.hex() + "$" + digest.hex()
def verify_password(password: str, stored: str | None) -> bool:
if not stored or "$" not in stored:
return False
try:
salt_hex, digest_hex = stored.split("$", 1)
salt = bytes.fromhex(salt_hex)
expected = bytes.fromhex(digest_hex)
except ValueError:
return False
actual = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 180_000)
return hmac.compare_digest(actual, expected)