Files
Uch-Practic/app/security.py

26 lines
872 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import hashlib
import secrets
def hash_password(password: str, salt: str | None = None) -> tuple[str, str]:
"""PBKDF2-SHA256 хэш пароля с солью."""
if salt is None:
salt = secrets.token_hex(16) # новая соль при регистрации
pwd_hash = hashlib.pbkdf2_hmac(
"sha256", password.encode("utf-8"), salt.encode("utf-8"), 100_000
).hex()
return pwd_hash, salt
def verify_password(password: str, salt: str, password_hash: str) -> bool:
"""Сравнивает пароль с сохранённым хэшем."""
new_hash, _ = hash_password(password, salt)
return secrets.compare_digest(new_hash, password_hash) # защита от timing-атак
def generate_token() -> str:
"""Генерирует случайный токен сессии."""
return secrets.token_hex(32)