On this page
secrets
Prev: sched | Up: stdlib_module | Next: select
Rel: hashlib, hmac
Ref: docs.python.org — secrets
Tags: #public #python3 #stdlib
Import
import secrets
Overview
Cryptographically strong random numbers and token generators backed by the OS CSPRNG (os.urandom). Always use secrets—never random—for API keys, session tokens, password-reset URLs, CSRF tokens, salts, and security-sensitive selection.
Quick Start
import secrets
api_token = secrets.token_urlsafe(32) # 256 bits of entropy, URL-safe base64
hex_id = secrets.token_hex(16) # 32 hex chars (128 bits)
roll = secrets.randbelow(6) + 1 # uniform integer in [1, 6]
assert len(hex_id) == 32 and 1 <= roll <= 6
Implementation Walkthrough
1. Constant-Time Token Verification (compare_digest)
Always compare secret tokens with secrets.compare_digest() to avoid leaking prefix match lengths via timing side channels:
import secrets
expected = secrets.token_urlsafe(32)
provided = expected # from an HTTP header or form field
assert secrets.compare_digest(expected, provided)
2. Generating Readable Passphrases or Temporary Codes
import secrets
import string
alphabet = string.ascii_letters + string.digits
temp_code = "".join(secrets.choice(alphabet) for _ in range(12))
assert len(temp_code) == 12
Gotchas & Boundaries
- Never use
randomfor security:randomuses Mersenne Twister, whose internal state can be reconstructed after observing outputs. - Argument to
token_hex(n)/token_urlsafe(n)is bytes, not characters:token_hex(32)returns 64 hex characters (256 bits of entropy). compare_digest()requires matching types: Comparestrtostr(ASCII) orbytestobytes; encode UTF-8 strings tobytesfirst if non-ASCII characters are possible.
Common Functions
- secrets.choice() —
choice(seq)— Choose a random element from a non-empty sequence. - secrets.compare_digest() —
compare_digest(a, b, /)— Return 'a == b'. - secrets.randbelow() —
randbelow(exclusive_upper_bound)— Return a random int in the range [0, n). - secrets.randbits() —
randbits(k)— getrandbits(k) -> x. Generates an int with k random bits. - secrets.token_bytes() —
token_bytes(nbytes=None)— Return a random byte string containing nbytes bytes. - secrets.token_hex() —
token_hex(nbytes=None)— Return a random text string, in hexadecimal. - secrets.token_urlsafe() —
token_urlsafe(nbytes=None)— Return a random URL-safe text string, in Base64 encoding.
Classes & Objects
- secrets.SystemRandom — Alternate random number generator using sources provided by the operating system (such as /dev/urandom on Unix or CryptGenRandom on Windows). (Methods:
.betavariate(),.binomialvariate(),.choice(),.choices(),.expovariate(),.gammavariate())
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/hashlib
- tuts/python3/stdlib_module/hmac
- tuts/python3/stdlib_module/os/urandom
- tuts/python3/stdlib_module/random
- tuts/python3/stdlib_module/sched
- tuts/python3/stdlib_module/secrets/choice
- tuts/python3/stdlib_module/secrets/compare_digest
- tuts/python3/stdlib_module/secrets/randbelow
- tuts/python3/stdlib_module/secrets/randbits
- tuts/python3/stdlib_module/secrets/SystemRandom
- tuts/python3/stdlib_module/secrets/token_bytes
- tuts/python3/stdlib_module/secrets/token_hex
- tuts/python3/stdlib_module/secrets/token_urlsafe
- tuts/python3/stdlib_module/select
- tuts/python3/stdlib_module/stdlib_module
Related notes
- tuts/python3/stdlib_module/hashlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/hmac Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/random Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sched Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/secrets/choice Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/secrets/compare_digest Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/secrets/randbelow Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/secrets/randbits Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/secrets/SystemRandom Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/secrets/token_bytes Linked here; links to this page; shared tags: #stdlib