Загрузить файлы в «app»
This commit is contained in:
25
app/security.py
Normal file
25
app/security.py
Normal file
@@ -0,0 +1,25 @@
|
||||
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)
|
||||
Reference in New Issue
Block a user