Skip to content

jam.utils.salt_hash

salt_hash

Utilities for secure password hashing and verification. Uses PBKDF2-HMAC-SHA256 with salt and constant-time comparison.

Functions:

Name Description
check_password

Verifies a password by recalculating the hash and comparing it to the stored hash.

deserialize_hash

Splits a stored string into salt and hash.

hash_password

Hashes a password with a salt using PBKDF2-HMAC-SHA256.

serialize_hash

Combines salt and hash into a single string for database storage.

check_password

check_password(
    password: str,
    salt_hex: str,
    hash_hex: str,
    iterations: int = 100000,
) -> bool

Verifies a password by recalculating the hash and comparing it to the stored hash.

Parameters:

Name Type Description Default
password str

Password to verify.

required
salt_hex str

Hex representation of the salt.

required
hash_hex str

Hex representation of the stored hash.

required
iterations int

Number of PBKDF2 iterations, must match the hashing call.

100000

Returns:

Name Type Description
bool bool

True if the password is correct, False otherwise.

Example
>>> salt, hash_ = hash_password("my_password")
>>> check_password("my_password", salt, hash_)
True
>>> check_password("wrong_password", salt, hash_)
False

# Using custom iterations
>>> salt, hash_ = hash_password("my_password", iterations=150_000)
>>> check_password("my_password", salt, hash_, iterations=150_000)
True

deserialize_hash

deserialize_hash(data: str) -> tuple[str, str]

Splits a stored string into salt and hash.

Example
>>> salt, hash_ = deserialize_hash("abcdef1234$9876543210")
>>> isinstance(salt, str)
True
>>> isinstance(hash_, str)
True

hash_password

hash_password(
    password: str,
    salt: Optional[bytes] = None,
    iterations: int = 100000,
    salt_size: int = 16,
) -> tuple[str, str]

Hashes a password with a salt using PBKDF2-HMAC-SHA256.

Parameters:

Name Type Description Default
password str

Password to hash.

required
salt bytes | None

Salt. If None, a random salt is generated.

None
iterations int

Number of PBKDF2 iterations.

100000
salt_size int

Size of the random salt in bytes.

16

Returns:

Type Description
tuple[str, str]

tuple[str, str]: (hex_salt, hex_hash)

Example
>>> salt, hash_ = hash_password("my_password")
>>> isinstance(salt, str)
True
>>> isinstance(hash_, str)
True

# Using custom iterations and salt size
>>> salt, hash_ = hash_password("my_password", iterations=150_000, salt_size=24)

serialize_hash

serialize_hash(salt_hex: str, hash_hex: str) -> str

Combines salt and hash into a single string for database storage.

Example
>>> salt, hash_ = hash_password("my_password")
>>> serialized = serialize_hash(salt, hash_)
>>> isinstance(serialized, str)
True

FILE PATH: jam/utils/salt_hash.py