Secrets Secure Token Generation
Generate cryptographically secure tokens with the secrets module, comparing them in constant time and binding usage scope per token.
Code
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:
hmacis 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
JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.