Source code for structum_lab.plugins.auth.password
# Argon2 Password Hasher
# SPDX-License-Identifier: Apache-2.0
"""
Password hashing using Argon2 (argon2-cffi).
"""
from argon2 import PasswordHasher # type: ignore[import-not-found]
from argon2.exceptions import VerifyMismatchError # type: ignore[import-not-found]
from structum_lab.auth.interfaces import PasswordHasherInterface
[docs]
class Argon2PasswordHasher(PasswordHasherInterface):
"""Argon2 implementation of PasswordHasherInterface."""
[docs]
def __init__(
self,
time_cost: int = 2,
memory_cost: int = 65536,
parallelism: int = 1,
hash_len: int = 32,
salt_len: int = 16,
) -> None:
"""Initialize the Argon2 password hasher.
Args:
time_cost: Number of iterations.
memory_cost: Memory usage in kibibytes.
parallelism: Number of parallel threads.
hash_len: Length of the hash output.
salt_len: Length of the random salt.
"""
self._ph = PasswordHasher(
time_cost=time_cost,
memory_cost=memory_cost,
parallelism=parallelism,
hash_len=hash_len,
salt_len=salt_len,
)
[docs]
def hash(self, password: str) -> str:
"""Hash a password."""
return str(self._ph.hash(password))
[docs]
def verify(self, password: str, hashed: str) -> bool:
"""Verify password against hash."""
try:
return bool(self._ph.verify(hashed, password))
except VerifyMismatchError:
return False