refactor: update hash_password and verify_password to use algorithm interface
This commit is contained in:
34
salt.py
34
salt.py
@@ -19,22 +19,15 @@ DEFAULT_ITERATIONS = int(os.environ.get("PBKDF2_ITERATIONS", "200000"))
|
||||
def hash_password(
|
||||
password: str,
|
||||
*,
|
||||
algorithm: str = "pbkdf2",
|
||||
iterations: int | None = None,
|
||||
salt_bytes: int = DEFAULT_SALT_BYTES,
|
||||
) -> tuple[str, str]:
|
||||
"""Return a base64 encoded salt and hash for ``password``."""
|
||||
iterations = iterations or DEFAULT_ITERATIONS
|
||||
salt = os.urandom(salt_bytes)
|
||||
derived = hashlib.pbkdf2_hmac(
|
||||
"sha256",
|
||||
password.encode("utf-8"),
|
||||
salt,
|
||||
iterations,
|
||||
)
|
||||
return (
|
||||
base64.b64encode(salt).decode("utf-8"),
|
||||
base64.b64encode(derived).decode("utf-8"),
|
||||
)
|
||||
from algorithms import get_algorithm
|
||||
|
||||
algo = get_algorithm(algorithm)
|
||||
return algo.hash(password, iterations=iterations, salt_bytes=salt_bytes)
|
||||
|
||||
|
||||
def verify_password(
|
||||
@@ -42,23 +35,14 @@ def verify_password(
|
||||
salt_b64: str,
|
||||
hash_b64: str,
|
||||
*,
|
||||
algorithm: str = "pbkdf2",
|
||||
iterations: int | None = None,
|
||||
) -> bool:
|
||||
"""Validate ``password`` against the provided base64 salt + hash pair."""
|
||||
iterations = iterations or DEFAULT_ITERATIONS
|
||||
try:
|
||||
salt = base64.b64decode(salt_b64, validate=True)
|
||||
stored_hash = base64.b64decode(hash_b64, validate=True)
|
||||
except (binascii.Error, ValueError):
|
||||
return False
|
||||
from algorithms import get_algorithm
|
||||
|
||||
derived = hashlib.pbkdf2_hmac(
|
||||
"sha256",
|
||||
password.encode("utf-8"),
|
||||
salt,
|
||||
iterations,
|
||||
)
|
||||
return hmac.compare_digest(derived, stored_hash)
|
||||
algo = get_algorithm(algorithm)
|
||||
return algo.verify(password, salt_b64, hash_b64, iterations=iterations)
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
|
||||
Reference in New Issue
Block a user