33 lines
1.1 KiB
Python
33 lines
1.1 KiB
Python
import os
|
|
|
|
from argon2 import PasswordHasher, Type
|
|
from argon2.exceptions import VerificationError, VerifyMismatchError
|
|
|
|
_memory = int(os.getenv('ARGON2_MEMORY_KIB', '19456'))
|
|
_iterations = int(os.getenv('ARGON2_ITERATIONS', '2'))
|
|
_parallelism = int(os.getenv('ARGON2_PARALLELISM', '1'))
|
|
if _memory < 19456 or _iterations < 2 or _parallelism < 1:
|
|
raise RuntimeError('Argon2id requires at least 19 MiB, t=2 and p=1')
|
|
|
|
_hasher = PasswordHasher(
|
|
memory_cost=_memory, time_cost=_iterations, parallelism=_parallelism, type=Type.ID,
|
|
)
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return _hasher.hash(password)
|
|
|
|
|
|
def password_matches(stored_hash: str, password: str) -> bool:
|
|
try:
|
|
return _hasher.verify(stored_hash, password)
|
|
except (VerifyMismatchError, VerificationError):
|
|
return False
|
|
|
|
|
|
def verify_and_upgrade(stored_hash: str, password: str) -> tuple[bool, str | None]:
|
|
if not password_matches(stored_hash, password):
|
|
return False, None
|
|
upgraded = hash_password(password) if _hasher.check_needs_rehash(stored_hash) else None
|
|
return True, upgraded
|