Skip to content

Password Hashing

lauren-guards ships two production-grade password hashers behind a common PasswordHasher protocol, plus a secure token generator.

PasswordHasher (Protocol)

from typing import Protocol

class PasswordHasher(Protocol):
    def hash(self, password: str) -> str: ...
    def verify(self, password: str, hashed: str) -> bool: ...

Both built-in hashers implement it. hash produces a self-describing hash (algorithm + parameters + salt embedded), and verify returns False — never raises — for wrong passwords and malformed hashes, so your auth flow can branch on the boolean.

Depend on the protocol, not the concrete class, so hashers can be swapped:

from lauren_guards import PasswordHasher

def auth_service(hasher: PasswordHasher): ...

BcryptHasher(*, rounds=12)

Requires: pip install "lauren-guards[bcrypt]".

from lauren_guards import BcryptHasher

hasher = BcryptHasher(rounds=12)   # 4..31; 12 is a sensible modern baseline

stored = hasher.hash("hunter2")
assert hasher.verify("hunter2", stored) is True
assert hasher.verify("wrong", stored) is False

rounds is the bcrypt cost factor (must be 4–31). Each hash uses a random salt, so the same password hashes differently every time.

Argon2Hasher(...)

Requires: pip install "lauren-guards[argon2]".

from lauren_guards import Argon2Hasher

hasher = Argon2Hasher()   # defaults follow the OWASP cheat sheet

Parameters (all keyword-only, all optional):

Parameter Default Meaning
time_cost 2 Iterations
memory_cost 19_456 (19 MiB) Memory used per hash
parallelism 1 Threads
hash_len 32 Output length (bytes)
salt_len 16 Random salt length (bytes)

Argon2id is memory-hard (resists GPU/ASIC attacks) and is OWASP's recommendation for new applications.

generate_token(length=32)

URL-safe, cryptographically secure random token (wraps secrets.token_urlsafe):

from lauren_guards import generate_token

token = generate_token()              # ~32 chars, URL-safe
session_id = generate_token(48)

Raises ValueError for length < 8. Useful for session ids, API keys, password-reset tokens, and CSRF cookie values.

Picking a hasher

  • bcrypt — the industry standard since 1999; widely supported across languages and tools.
  • argon2 — PHC winner (2015), memory-hard; recommended by OWASP for new apps.

Both are interchangeable behind PasswordHasher, so migrating is a one-line change (store both old and new hashes side-by-side during a transition window: verify against the format prefix).