Skip to content
Tutorials Center
My learning

Topics

Python Reference · Standard Library: Math, Data and Text

The secrets module

Reference for Python's secrets module: cryptographically strong tokens, passwords, random choices, compare_digest, and why random is not safe for secrets.

The secrets module generates random values that are safe to use for security: password reset tokens, session identifiers, API keys, one-time codes and temporary passwords. It draws from the operating system's secure random source, so values cannot be predicted from earlier output, which is not true for the random module.

The module is small. A few token_* functions return random bytes in different formats, choice() and randbelow() pick random items and numbers securely, and compare_digest() compares secrets without leaking information through timing.

Python
import secrets

token = secrets.token_urlsafe(16)

Try it

Python Tokens and passwords

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python A password that meets rules, and safe comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Frequently used names

Name Description
token_bytes(nbytes=None) nbytes random bytes.
token_hex(nbytes=None) Random text in hexadecimal; the string is 2 * nbytes characters long.
token_urlsafe(nbytes=None) Random text using the URL-safe Base64 alphabet (A-Z a-z 0-9 - _), about 1.3 * nbytes characters, without padding. Safe in URLs and file names.
choice(sequence) One randomly chosen element.
randbelow(n) Random integer from 0 up to but not including n.
randbits(k) Random integer with k random bits.
compare_digest(a, b) Compares two strings (ASCII only) or two bytes-like objects in constant time. Returns a bool.
SystemRandom The random.Random API (shuffle, sample, uniform...) using the operating system's source.
DEFAULT_ENTROPY The number of bytes used when nbytes is omitted. It can change between versions, so do not rely on a specific number.

Usage notes

  • Use secrets for anything an attacker must not guess. random.choice and random.randint are predictable if someone observes enough outputs. Never generate tokens, passwords or reset codes with them.
  • How many bytes? At least 32 bytes (256 bits) is a comfortable amount for tokens that protect accounts. 16 bytes (128 bits) is the usual minimum. The nbytes argument counts raw random bytes, not characters in the final text.
  • Do not truncate or edit tokens and do not mix them with timestamps or user IDs; keep tokens opaque. Store only a hash of long-lived tokens in your database, just like passwords.
  • Use compare_digest() to check tokens, signatures and password hashes. An ordinary == stops at the first difference, so response time can reveal how many leading characters were right. compare_digest takes the same time wherever the difference is.
  • Strings passed to compare_digest must be ASCII. Encode non-ASCII text to bytes first, as the example shows.
  • Passwords from users should not be stored with secrets. It generates new random values; to store a password, hash it with a slow, salted function such as hashlib.scrypt, bcrypt or Argon2.
  • Not reproducible. secrets has no seed() on purpose, so tests that need fixed values should inject the generated value or use random with a seed instead.
  • Availability. Added in Python 3.6. The functions never fall back to weak data; if the system cannot supply secure randomness, they fail instead.
  • UUIDs. uuid.uuid4() is also random, but a secrets token is the clearer choice for security tokens.