44 lines
1.4 KiB
Python
44 lines
1.4 KiB
Python
"""Password hashing with Argon2id (library KDF, salted, versioned parameters)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from argon2 import PasswordHasher
|
|
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
|
|
|
|
|
# OWASP-recommended Argon2id baseline: 19 MiB, 2 iterations, 1 lane.
|
|
_hasher = PasswordHasher(
|
|
time_cost=2,
|
|
memory_cost=19456,
|
|
parallelism=1,
|
|
hash_len=32,
|
|
salt_len=16,
|
|
)
|
|
|
|
# Verified against when a username is unknown, so the failure path costs the same
|
|
# as a wrong password and does not leak username existence through timing.
|
|
_DUMMY_HASH = _hasher.hash("dummy-password-not-used-for-any-account")
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return _hasher.hash(password)
|
|
|
|
|
|
def verify_password(password: str, encoded: str | None) -> bool:
|
|
"""Return True only for a matching password and a parseable hash."""
|
|
if encoded is None:
|
|
verify_password_unknown_user(password)
|
|
return False
|
|
try:
|
|
return _hasher.verify(encoded, password)
|
|
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
|
return False
|
|
|
|
|
|
def verify_password_unknown_user(password: str) -> None:
|
|
"""Burn comparable CPU time when no account exists for the username."""
|
|
try:
|
|
_hasher.verify(_DUMMY_HASH, password)
|
|
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
|
return
|