secrets
The Python secrets module provides a straightforward and secure way to generate cryptographically strong random numbers suitable for managing sensitive data, such as passwords, account credentials, security tokens, and related secrets.
Here’s a quick example:
>>> import secrets
>>> # Generate a secure random number
>>> secrets.randbelow(10)
4
Key Features
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
secrets.token_bytes() |
Function | Generates a random byte string |
secrets.token_hex() |
Function | Generates a random text string, in hexadecimal |
secrets.token_urlsafe() |
Function | Generates a random URL-safe text string |
secrets.choice() |
Function | Returns a randomly chosen element from a non-empty sequence |
secrets.randbelow() |
Function | Returns a random int in the range [0, n) |
secrets.randbits() |
Function | Returns a non-negative int with k random bits |
secrets.compare_digest() |
Function | Compares two strings in constant time to reduce the risk of timing attacks |
secrets.SystemRandom |
Class | Generates random numbers using the highest-quality sources provided by the operating system |
secrets.DEFAULT_ENTROPY |
Constant | Default number of bytes of randomness used by the module’s token_* functions when nbytes is omitted or None |
Examples
Generate a random byte string:
>>> secrets.token_bytes(16)
b'1Y\x80\x10rG \xa9J\xd0\x9c\x9f\x13\xd3\x98\xb1'
Generate a random text string in hexadecimal:
>>> secrets.token_hex(16)
'2befb22f1581dd4ede4821e6252d1359'
Generate a random URL-safe text string:
>>> secrets.token_urlsafe(16)
'JOQrXog1v_aK6QgZp9Lxrg'
Common Use Cases
- Generating secure tokens for session management
- Creating cryptographically secure passwords
- Comparing sensitive data in a secure manner
Real-World Example
Suppose you’re building a web application and need to generate secure tokens for user sessions. Here’s how you can use the secrets module to create a token:
>>> import secrets
>>> token = secrets.token_urlsafe(32)
>>> print(f"Your session token is: {token}")
Your session token is: eMWcxNGqfiucn-SjezajTtOEX7M5D81n3rRL6r06yxM
In this example, the secrets module generates a secure, random URL-safe token suitable for managing user sessions.
Related Resources
Tutorial
Generating Random Data in Python (Guide)
You'll cover a handful of different options for generating random data in Python, and then build up to a comparison of each in terms of its level of security, versatility, purpose, and speed.
For additional information on related topics, take a look at the following resources:
- Generating Random Data in Python (Course)
By Leodanis Pozo Ramos • Updated Aug. 3, 2026