rewrited logic structure
This commit is contained in:
26
group_system/security.py
Normal file
26
group_system/security.py
Normal 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)
|
||||
Reference in New Issue
Block a user