Secrets Secure Token Generation

Generate cryptographically secure tokens with the secrets module, comparing them in constant time and binding usage scope per token.

PythonSecurity Boundaries

Code

pythonsnippet
42 lines
import hmac
import secrets

ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'


def api_key(prefix: str = 'sk') -> str:
    body = ''.join(secrets.choice(ALPHABET) for _ in range(40))
    return f'{prefix}_{body}'


def url_token(nbytes: int = 32) -> str:
    return secrets.token_urlsafe(nbytes)


def otp_code(digits: int = 6) -> str:
    # 朴素做法 random.randint 可预测,必须用 secrets
    floor = 10 ** (digits - 1)
    return str(floor + secrets.randbelow(9 * floor))


def constant_time_match(candidate: str, expected: str) -> bool:
    if len(candidate) != len(expected):
        return False
    return hmac.compare_digest(
        candidate.encode(), expected.encode()
    )


def scoped_token(scope: str, nbytes: int = 16) -> dict:
    return {
        'token': url_token(nbytes),
        'scope': scope,
        'hint': f'scope={scope}',
    }


key = api_key()
code = otp_code()
print('key length:', len(key), 'otp:', code)
print('compare ok:', constant_time_match(code, code))
print('compare tampered:', constant_time_match(code, '123456'))

Inside the snippet

The working surface is the functions api_key, url_token, otp_code and constant_time_match — everything else is wiring.

It builds and returns a fresh value rather than reusing its inputs.

Caveats

  • Plan for an install step: hmac is a real dependency, resolved by the package manager.

Using it

Entry signature: def api_key(prefix: str = 'sk') -> str

Running the file prints labeled results such as key length:, compare ok:, compare tampered: — each operation’s effect is visible in the output.

api_key is what another module would consume; nothing else here is load-bearing for callers.

Key statements

def constant_time_match(candidate: str, expected: str) -> bool:
    if len(candidate) != len(expected):
        return False
    return hmac.compare_digest(
        candidate.encode(), expected.encode()
    )
def scoped_token(scope: str, nbytes: int = 16) -> dict:
    return {
        'token': url_token(nbytes),
        'scope': scope,
        'hint': f'scope={scope}',
    }
def api_key(prefix: str = 'sk') -> str:
    body = ''.join(secrets.choice(ALPHABET) for _ in range(40))
    return f'{prefix}_{body}'

Interactive Tools for This Topic

FAQ

Does `api_key` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Are there third-party dependencies?
`hmac` — install it with the package manager before running.