Skip to content

Cryptography

reauth.crypto

A set of cryptographic utilities.

TokenHash module-attribute

TokenHash = typing.NewType('TokenHash', str)

get_token_hash

get_token_hash(token: str, *, secret: str) -> TokenHash

Compute HMAC-SHA256 hash of a token.

Parameters:

Name Type Description Default
token str

The token value to hash.

required
secret str

The secret key used for HMAC computation.

required

Returns:

Type Description
TokenHash

Hexadecimal string of the HMAC-SHA256 hash.

generate_token

generate_token(*, prefix: str = '') -> str

Generate a high-entropy random token with embedded checksum.

The token consists of a random string of 37 alphanumeric characters followed by a 6-character base62-encoded CRC32 checksum.

The CRC32 checksum provides fast pre-validation to filter out malformed or corrupted tokens before more expensive HMAC verification or database lookups. It is NOT a cryptographic security mechanism.

Parameters:

Name Type Description Default
prefix str

Optional prefix prepended to the generated token.

''

Returns:

Type Description
str

A token string with format: {prefix}{37_random_chars}{6_checksum_chars}.

generate_token_hash_pair

generate_token_hash_pair(
    *, secret: str, prefix: str = ""
) -> tuple[str, TokenHash]

Generate a token and its HMAC-SHA256 hash pair.

Generates a high-entropy token with embedded checksum and computes its HMAC-SHA256 hash using the provided secret. This pattern allows storing only the hash in the database while the raw token is provided to the user.

Parameters:

Name Type Description Default
secret str

The secret key used for HMAC computation.

required
prefix str

Optional prefix prepended to the generated token.

''

Returns:

Type Description
str

A tuple of (token, hash) where token is the raw value and hash is

TokenHash

its HMAC-SHA256 hexadecimal digest.

generate_code_hash_pair

generate_code_hash_pair(
    *, secret: str, length: int = 6
) -> tuple[str, TokenHash]

Generate a 6-alphanumeric code and its HMAC-SHA256 hash pair.

This is useful for generating OTP codes where the raw code is sent to the user and only the hash is stored for verification.

Parameters:

Name Type Description Default
secret str

The secret key used for HMAC computation.

required
length int

The length of the numeric code to generate (default is 6).

6

Returns:

Type Description
str

A tuple of (code, hash) where code is the raw code and hash is

TokenHash

its HMAC-SHA256 hexadecimal digest.