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:
Python
>>> 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.randbelow() |
Function | Returns a random int in the range [0, n) |
secrets.compare_digest() |
Function | Securely compares two strings to prevent timing attacks |
Examples
Generate a random byte string:
Python
>>> secrets.token_bytes(16)
b'1Y\x80\x10rG \xa9J\xd0\x9c\x9f\x13\xd3\x98\xb1'
Generate a random text string in hexadecimal:
Python
>>> secrets.token_hex(16)
'2befb22f1581dd4ede4821e6252d1359'
Generate a random URL-safe text string:
Python
>>> 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:
Python
>>> 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.
By Leodanis Pozo Ramos • Updated July 17, 2025