30 lines
903 B
Python
30 lines
903 B
Python
"""Хеширование паролей (Argon2id) и генерация opaque-токенов сессий."""
|
||
import hashlib
|
||
import secrets
|
||
|
||
from argon2 import PasswordHasher
|
||
from argon2.exceptions import VerifyMismatchError, VerificationError, InvalidHashError
|
||
|
||
_hasher = PasswordHasher()
|
||
|
||
|
||
def hash_password(password: str) -> str:
|
||
return _hasher.hash(password)
|
||
|
||
|
||
def verify_password(password_hash: str, password: str) -> bool:
|
||
try:
|
||
return _hasher.verify(password_hash, password)
|
||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||
return False
|
||
|
||
|
||
def new_token() -> str:
|
||
"""256 бит энтропии, URL-safe."""
|
||
return secrets.token_urlsafe(32)
|
||
|
||
|
||
def token_hash(token: str) -> str:
|
||
"""В БД/Redis храним только SHA-256 от токена, не сам токен."""
|
||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|