import asyncio import secrets from argon2 import PasswordHasher, Type from argon2.exceptions import InvalidHashError, VerificationError TIME_COST = 2 MEMORY_COST_KIB = 19_456 PARALLELISM = 1 class Argon2PasswordHasher: __slots__ = ("_dummy", "_hasher", "_slots") def __init__(self, concurrency: int) -> None: self._hasher = PasswordHasher( time_cost=TIME_COST, memory_cost=MEMORY_COST_KIB, parallelism=PARALLELISM, type=Type.ID, ) self._slots = asyncio.Semaphore(concurrency) self._dummy = self._hasher.hash(secrets.token_urlsafe(16)) async def hash(self, password: str) -> str: async with self._slots: return await asyncio.to_thread(self._hasher.hash, password) async def verify(self, password_hash: str | None, password: str) -> bool: async with self._slots: try: await asyncio.to_thread(self._hasher.verify, password_hash or self._dummy, password) except VerificationError, InvalidHashError: return False return password_hash is not None