Skip to content

xtr_password_hasher

Password hashing behind one interface.

argon2id by default, legacy hashes verified and upgraded.

MAX_PASSWORD_LENGTH module-attribute

MAX_PASSWORD_LENGTH: Final = 4096

The greatest input length, in UTF-8 bytes, any hasher processes.

A longer input is refused by :meth:PasswordHasherInterface.hash — an unbounded input would let a caller spend a hasher's whole cost on one call — and rejected by :meth:PasswordHasherInterface.verify as a non-match. The bound is on the encoded byte length, since that is the work a hasher reads: a multi-byte character costs its bytes. It is a denial-of-service guard, not a rule on how long a password may be.

InvalidArgumentError

InvalidArgumentError(reason: str)

Bases: PasswordHasherError, ValueError

A hasher or a config was configured with a value it cannot use.

Raised where the value is given — a bcrypt cost outside 4 to 31, a PBKDF2 iteration count below a safe floor, a hash algorithm the platform does not provide, an algorithm no hasher implements, rather than on the first hash.

Also a :class:ValueError, so code that already guards its configuration with except ValueError keeps working without learning a new exception.

Attributes:

  • reason (str) –

    What is wrong with the argument.

Record what is wrong with the argument.

InvalidPasswordError

InvalidPasswordError(length: int, max_length: int)

Bases: PasswordHasherError, ValueError

A plaintext password exceeded the length a hasher accepts.

Raised by :meth:hash when the input is longer than MAX_PASSWORD_LENGTH. Refusing an unbounded input keeps a hasher from spending unbounded work on it — a denial-of-service guard, not a policy on how long a password may be. Verifying an over-long input never raises: it simply cannot match a hash made from a bounded one, so :meth:verify returns False.

Also a :class:ValueError, so code that already guards its input with except ValueError keeps working without learning a new exception.

Attributes:

  • length (int) –

    The UTF-8 byte length of the input that was refused.

  • max_length (int) –

    The greatest UTF-8 byte length a hasher accepts.

Record the refused UTF-8 byte length and the limit it crossed.

PasswordHasherError

Bases: Exception

Base class for every error raised by this library.

Catch this to handle anything hashing can go wrong with; catch a subclass to handle one cause. Every subclass carries the data a caller needs as typed attributes and composes its own message from them.

UnknownPasswordHasherError

UnknownPasswordHasherError(looked_up: str)

Bases: PasswordHasherError, LookupError

The factory holds no hasher for the user, class or name asked for.

Raised by :meth:~xtr_password_hasher.PasswordHasherFactoryInterface.get_password_hasher when nothing in its mapping matches — no entry for the class or any of its bases, no entry for the name the user declares, and no entry for the string key given. The message names what was looked up so the fix is to add that key to the factory's mapping.

Also a :class:LookupError, so a caller may catch either this type or the built-in.

Attributes:

  • looked_up (str) –

    What was searched for — a class's qualified name, or the string key given.

Record what had no hasher, and how to fix it.

MigratingPasswordHasher

MigratingPasswordHasher(best: PasswordHasherInterface, *extras: PasswordHasherInterface)

Bases: PasswordHasherInterface

Hashes with one preferred hasher, verifies with it and older ones behind it.

A deployment holding hashes from several eras keeps this in front: new passwords are hashed with best, and a stored hash best does not recognise is offered to each of extras in turn. A hash best already owns never reaches the extras, so the common path pays for one verify.

A salt given to :meth:hash or :meth:verify is passed on to each hasher that takes one — a :class:~xtr_password_hasher.LegacyPasswordHasherInterface, or another migrating hasher — and left out for the self-salting ones, so a legacy salted hash verifies behind an argon2id front.

Paired with :meth:needs_rehash — which delegates to best — a login verified against a legacy hash is the moment to rehash and upgrade it. Never put a :class:~xtr_password_hasher.PlaintextPasswordHasher among the extras: a leaked hash would then be a working password.

Hash with best; fall back to extras only for hashes it disowns.

Raises:

  • InvalidArgumentError –

    When an extra is a :class:~xtr_password_hasher.PlaintextPasswordHasher; it "verifies" any string equal to the stored one, so behind a migrating hasher a leaked hash would be a working password.

hash

hash(plain_password: str, salt: str | None = None) -> str

Hash plain_password with the preferred hasher.

Raises:

verify

verify(hashed_password: str, plain_password: str, salt: str | None = None) -> bool

Return whether plain_password made hashed_password, best hasher first.

When best recognises hashed_password — it does not need rehashing to the best format — only best verifies it. Otherwise each extra is tried, then best once more as a last resort.

needs_rehash

needs_rehash(hashed_password: str) -> bool

Return whether hashed_password should be replaced, as the best hasher sees it.

NativePasswordHasher

NativePasswordHasher(algorithm: Algorithm = 'argon2id', *, time_cost: int = 3, memory_cost: int = 65536, parallelism: int = 4, cost: int = 12)

Bases: PasswordHasherInterface

Hashes with argon2id or bcrypt, and verifies either when its backend is installed.

Argon2id is the default: memory-hard, so a stolen hash is dear to attack on commodity hardware. bcrypt is available for interoperability — it needs the bcrypt extra — and, because bcrypt reads at most 72 bytes, a longer input is folded to a fixed length first (the base64 of its SHA-512 digest, truncated to what bcrypt reads) on both hashing and verifying, so a long password stays stable across the two.

Whichever algorithm it hashes with, it verifies a hash of either as long as that algorithm's backend is present, so hashes minted by another stack — $argon2id$… or $2a$/$2b$/$2y$ — migrate in place. :meth:needs_rehash asks for a fresh hash whenever a stored one is of the other algorithm, or of weaker parameters.

Configure the active algorithm and every backend that is installed.

The active algorithm decides how :meth:hash writes; both backends are prepared for verifying when their libraries are present, so a migrating deployment reads legacy hashes of either.

Raises:

  • InvalidArgumentError –

    When algorithm is neither "argon2id" nor "bcrypt", an argon2 cost is not positive, the bcrypt cost is outside 4 to 31, or algorithm="bcrypt" is asked for without the bcrypt extra installed.

hash

hash(plain_password: str) -> str

Hash plain_password with the active algorithm.

Raises:

verify

verify(hashed_password: str, plain_password: str) -> bool

Return whether plain_password made hashed_password, by the backend owning it.

needs_rehash

needs_rehash(hashed_password: str) -> bool

Return whether hashed_password should be replaced by a fresh hash.

True when hashed_password belongs to the other algorithm, is unrecognised, or was made with weaker parameters than the active backend now uses.

PasswordHasherAwareInterface

Bases: Protocol

A user that chooses its hasher by name rather than by its class.

The factory asks this first: a user that answers with a name is hashed by the entry mapped to that name, whatever its class. A None answer means "decide by my class instead", the usual case.

get_password_hasher_name

get_password_hasher_name() -> str | None

Return the name of the hasher to use, or None to decide by class.

PasswordHasherFactory

PasswordHasherFactory(password_hashers: Mapping[type | str, PasswordHasherInterface])

Bases: PasswordHasherFactoryInterface

Hands out a hasher per user, chosen from a mapping keyed by class or name.

A key is a user class, a "module:Class" string, or a name a user declares through :class:~xtr_password_hasher.PasswordHasherAwareInterface. Resolution, in order:

  1. a user that declares a hasher name is looked up by that name;
  2. otherwise the user's class — the class itself, or type(user) — is walked up its __mro__, matching a class key or the matching "module:Class" string at each step;
  3. a bare name or "module:Class" string passed in is looked up as it is.

A mapping value is a ready hasher. Turning inert configuration into a live hasher — argon2 costs, migrating chains, a hasher a container provides — is the caller's job, so the factory carries no configuration vocabulary and hashes standalone from the same instances a bundle would build.

Resolve users against password_hashers, keyed by class or name.

get_password_hasher

get_password_hasher(user: _User) -> PasswordHasherInterface

Return the hasher for user.

Raises:

PasswordHasherFactoryInterface

Bases: Protocol

Resolves which hasher a user, a class or a name is hashed by.

One application may hash different users differently — a slow argon2 for people, a cheap one for machine accounts — so the hasher is chosen per user, not fixed once.

get_password_hasher

get_password_hasher(user: str | type | PasswordAuthenticatedUserInterface | PasswordHasherAwareInterface) -> PasswordHasherInterface

Return the hasher for user.

Parameters:

Raises:

Pbkdf2PasswordHasher

Pbkdf2PasswordHasher(algorithm: str = 'sha512', encode_hash_as_base64: bool = True, iterations: int = 1000, length: int = 40)

Bases: LegacyPasswordHasherInterface

Derives a key with PBKDF2-HMAC and stores only the encoded key.

For verification of legacy hashes only: new passwords belong on a memory-hard hasher. The hash is the derived key alone — base64, or hex — so the salt lives beside it and the algorithm, the work factor and the key length live in this hasher's configuration. That is the shape of hashes many older applications stored; this hasher exists to verify them, and its defaults are the ones those hashes were typically made with. A None salt hashes with an empty one.

Since the hash carries no parameters, :meth:needs_rehash cannot tell a weak hash from a strong one and always answers False; put this hasher behind a self-salting one in a :class:~xtr_password_hasher.MigratingPasswordHasher to upgrade what it verifies.

Configure the digest, the encoding, the work factor and the derived-key length.

Parameters:

  • algorithm (str, default: 'sha512' ) –

    The digest PBKDF2 runs HMAC over.

  • encode_hash_as_base64 (bool, default: True ) –

    Encode the derived key as base64; as hex when False.

  • iterations (int, default: 1000 ) –

    How many times the digest is applied.

  • length (int, default: 40 ) –

    The derived key's length, in bytes.

Raises:

  • InvalidArgumentError –

    When PBKDF2 cannot run algorithm on this platform, or the iteration count or key length is not positive.

hash

hash(plain_password: str, salt: str | None = None) -> str

Derive a key from plain_password under salt and encode it.

Raises:

verify

verify(hashed_password: str, plain_password: str, salt: str | None = None) -> bool

Return whether plain_password under salt derives to hashed_password.

A hash of the wrong length, or one in a $-delimited format, is rejected before any key is derived.

needs_rehash

needs_rehash(hashed_password: str) -> bool

Return False: the hash carries no parameters to compare.

PlaintextPasswordHasher

PlaintextPasswordHasher(ignore_password_case: bool = False)

Bases: LegacyPasswordHasherInterface

Stores the password as it is; verifies by constant-time comparison.

For tests and fixtures, never production: the "hash" is the plaintext, followed by {salt} when a salt is given. It exists so a test suite can run without paying argon2's cost. Never put it among a migrating hasher's extras: a leaked hash would then be a working password.

Compare passwords case-insensitively when ignore_password_case is set.

hash

hash(plain_password: str, salt: str | None = None) -> str

Return plain_password, merged with salt, after the shared length guard.

Raises:

verify

verify(hashed_password: str, plain_password: str, salt: str | None = None) -> bool

Return whether plain_password under salt equals hashed_password.

Raises:

needs_rehash

needs_rehash(hashed_password: str) -> bool

Return False: a plaintext store has nothing to upgrade to.

UserPasswordHasher

UserPasswordHasher(factory: PasswordHasherFactoryInterface)

Bases: UserPasswordHasherInterface

Hashes and checks a password for a user, using the hasher its factory chooses.

Every call resolves the user's hasher through the factory, so one application can hash different users differently while callers only ever hand over the user and the plaintext. A :class:~xtr_password_hasher.LegacyPasswordAuthenticatedUserInterface user's salt goes to the hasher with the password.

Resolve each user's hasher through factory.

hash_password

hash_password(user: PasswordAuthenticatedUserInterface, plain_password: str) -> str

Hash plain_password with the hasher chosen for user.

Raises:

is_password_valid

is_password_valid(user: PasswordAuthenticatedUserInterface, plain_password: str) -> bool

Return whether plain_password matches user's stored password.

A user whose stored password is None returns False at once, without hashing plain_password. The early return is observable in time, so the timing guard is not this hasher's to keep: the caller that must not reveal which accounts have a password owns it, and the credentials listener is the caller that charges one — burning a dummy verify for the passwordless user.

Raises:

needs_rehash

needs_rehash(user: PasswordAuthenticatedUserInterface) -> bool

Return whether user's stored password should be rehashed.

Raises:

UserPasswordHasherInterface

Bases: Protocol

Hashes and verifies a password for a user, choosing the hasher by the user.

A thin seam over the factory: it picks the right hasher for the user's class or declared name, so callers hand it the user and the plaintext and never touch a hasher directly.

hash_password

hash_password(user: PasswordAuthenticatedUserInterface, plain_password: str) -> str

Hash plain_password with the hasher chosen for user.

Raises:

is_password_valid

is_password_valid(user: PasswordAuthenticatedUserInterface, plain_password: str) -> bool

Return whether plain_password matches user's stored password.

False when the user carries no password, so there is nothing to match against.

Raises:

needs_rehash

needs_rehash(user: PasswordAuthenticatedUserInterface) -> bool

Return whether user's stored password should be rehashed.

False when the user carries no password.

Raises:

LegacyPasswordAuthenticatedUserInterface

Bases: PasswordAuthenticatedUserInterface, Protocol

A user whose password was hashed under a salt it keeps separately.

The user password hasher hands the salt to a :class:~xtr_password_hasher.LegacyPasswordHasherInterface. Once every stored hash has been upgraded to a self-salting algorithm, implement :class:~xtr_password_hasher.PasswordAuthenticatedUserInterface instead.

get_salt

get_salt() -> str | None

Return the salt the password was originally hashed with, or None.

LegacyPasswordHasherInterface

Bases: PasswordHasherInterface, Protocol

A hasher that takes its salt from the caller rather than minting one.

Older schemes store the salt in a column of its own and the bare digest in another; the hash alone cannot be verified. Such a hasher is kept to read those hashes and upgrade them — new passwords belong to a self-salting hasher. A None salt means no salt at all.

Every method name matches :class:PasswordHasherInterface, so an isinstance check cannot tell the two apart; ask :func:is_legacy_password_hasher instead.

hash

hash(plain_password: str, salt: str | None = None) -> str

Hash plain_password under salt.

Raises:

  • InvalidPasswordError –

    When plain_password is longer than :data:~xtr_password_hasher.MAX_PASSWORD_LENGTH.

verify

verify(hashed_password: str, plain_password: str, salt: str | None = None) -> bool

Return whether plain_password under salt made hashed_password.

PasswordAuthenticatedUserInterface

Bases: Protocol

A user whose identity can be proven by a password.

The hasher factory keys on this: a user that carries a password is hashed and verified by whichever hasher its class is mapped to. The password is the stored hash, not the plaintext — None when the user has no password and so cannot authenticate by one.

get_password

get_password() -> str | None

Return the stored password hash, or None when there is none.

PasswordHasherInterface

Bases: Protocol

Turns a plaintext password into a hash, and checks one against it.

A hash is opaque: it names its own algorithm, parameters and salt, so the same hasher — or one built from a later, stronger configuration — reads them back to verify and to decide whether the hash should be replaced. A hasher whose salt is stored beside the hash instead is a :class:~xtr_password_hasher.LegacyPasswordHasherInterface.

hash

hash(plain_password: str) -> str

Hash plain_password and return the hash to store.

Parameters:

  • plain_password (str) –

    The plaintext password.

Raises:

verify

verify(hashed_password: str, plain_password: str) -> bool

Return whether plain_password is the password hashed_password was made from.

Never raises for an over-long plain_password: it cannot match a hash of a bounded input, so the answer is False. The comparison is constant-time.

needs_rehash

needs_rehash(hashed_password: str) -> bool

Return whether hashed_password should be replaced by a fresh hash.

True when hashed_password was made by a weaker algorithm or with weaker parameters than this hasher now uses — the moment to rehash the plaintext, which is only in hand right after a successful verify.

bcrypt_available

bcrypt_available() -> bool

Return whether the bcrypt backend can actually be loaded.

pwdlib ships the pwdlib.hashers.bcrypt module whether or not the bcrypt library behind it is installed, so merely finding the module answers True for a missing backend. An import probe — importing it, the way the native hasher builds its backend — is the reliable check: it raises when bcrypt is absent.

create_auto_password_hasher

create_auto_password_hasher() -> PasswordHasherInterface

Build argon2id with bcrypt (when installed) and PBKDF2 verifying behind it.

is_legacy_password_hasher

is_legacy_password_hasher(hasher: PasswordHasherInterface) -> TypeGuard[LegacyPasswordHasherInterface]

Return whether hasher declares :class:LegacyPasswordHasherInterface.

The check is by inheritance, not by shape: a structural match would accept every hasher, since the two interfaces share their method names and differ only in the salt parameter.