Files
mtusi2026lab7/src/app/security.py
T
SAMURAI 579bcc0b97
Skeleton contracts / contracts (pull_request) Canceled after 0s
Щербацевич-БПИ2302-на 3
2026-11-27 22:15:42 +03:00

68 lines
2.1 KiB
Python

import base64
import binascii
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMismatchError
from argon2.low_level import Type
# Ниже минимума lab7 (19 MiB, t=2, p=1) процесс не стартует.
_MIN_MEMORY_KIB = 19456
_MIN_TIME_COST = 2
_MIN_PARALLELISM = 1
_hasher: PasswordHasher | None = None
_dummy_hash: str | None = None
def init_security(memory_kib: int, iterations: int, parallelism: int) -> None:
global _hasher, _dummy_hash
if memory_kib < _MIN_MEMORY_KIB or iterations < _MIN_TIME_COST or parallelism < _MIN_PARALLELISM:
raise SystemExit("argon2 parameters are below the lab7 minimum")
if _hasher is None:
_hasher = PasswordHasher(
time_cost=iterations,
memory_cost=memory_kib,
parallelism=parallelism,
hash_len=32,
salt_len=16,
type=Type.ID,
)
if _dummy_hash is None:
_dummy_hash = _hasher.hash("messenger-dummy-password-not-used-for-login")
def get_hasher() -> PasswordHasher:
if _hasher is None:
raise SystemExit("password hasher is not initialized")
return _hasher
def hash_password(password: str) -> str:
return get_hasher().hash(password)
def verify_password(password: str, password_hash: str | None) -> bool:
try:
get_hasher().verify(password_hash or _dummy_hash, password)
matched = True
except (VerifyMismatchError, InvalidHashError):
matched = False
return password_hash is not None and matched
def parse_basic(header: str) -> tuple[str, str] | None:
if not header:
return None
scheme, _, rest = header.partition(" ")
if scheme.lower() != "basic" or not rest.strip():
return None
try:
decoded = base64.b64decode(rest.strip(), validate=True)
text = decoded.decode("utf-8")
except (ValueError, UnicodeError, binascii.Error):
return None
username, separator, password = text.partition(":")
if separator != ":" or len(username) > 256 or len(password) > 1024:
return None
return username, password