Skip to content

Reference

Modern password hashing for Python

PasswordHash

Represents a password hashing utility.

__init__(hashers)

Parameters:

Name Type Description Default
hashers Sequence[HasherProtocol]

A sequence of hashers to be used for password hashing.

required

Raises:

Type Description
AssertionError

If no hashers are specified.

hash(password, *, salt=None)

Hashes a password using the current hasher.

Parameters:

Name Type Description Default
password Union[str, bytes]

The password to be hashed.

required
salt Union[bytes, None]

The salt to be used for hashing. Defaults to None.

None

Returns:

Type Description
str

The hashed password.

Examples:

>>> hash = password_hash.hash("herminetincture")

recommended() classmethod

Returns a PasswordHash instance with recommended hashers.

Currently, the hasher is Argon2 with default parameters.

Examples:

>>> password_hash = PasswordHash.recommended()
>>> hash = password_hash.hash("herminetincture")
>>> password_hash.verify(hash, "herminetincture")
True

verify(password, hash)

Verifies if a password matches a given hash.

Parameters:

Name Type Description Default
password Union[str, bytes]

The password to be checked.

required
hash Union[str, bytes]

The hash to be verified.

required

Returns:

Type Description
bool

True if the password matches the hash, False otherwise.

Raises:

Type Description
UnknownHashError

If the hash is not recognized by any of the hashers.

Examples:

>>> password_hash.verify("herminetincture", hash)
True
>>> password_hash.verify("INVALID_PASSWORD", hash)
False

verify_and_update(password, hash)

Verifies if a password matches a given hash and updates the hash if necessary.

Parameters:

Name Type Description Default
password Union[str, bytes]

The password to be checked.

required
hash Union[str, bytes]

The hash to be verified.

required

Returns:

Type Description
Tuple[bool, Union[str, None]]

A tuple containing a boolean indicating if the password matches the hash, and an updated hash if the current hasher or the hash itself needs to be updated.

Raises:

Type Description
UnknownHashError

If the hash is not recognized by any of the hashers.

Examples:

>>> valid, updated_hash = password_hash.verify_and_update("herminetincture", hash)