Python secrets Module
Example
Generate a secure random token:
import secrets
token = secrets.token_hex(16)
print(f'Secure token: {token}')
Try it Yourself »
Definition and Usage
The secrets module generates cryptographically strong random numbers suitable for security purposes.
Use it to generate secure tokens, passwords, security keys, or any data that requires true randomness for security applications.
Note: Always use this module instead of the random module for security-related tasks like generating passwords or authentication tokens.
Members
Member | Description |
---|---|
SystemRandom | Class using os.urandom() for cryptographically secure randomness. |
choice() | Return a randomly chosen element from a non-empty sequence. |
randbelow() | Return a random integer in the range [0, n). |
randbits() | Return an integer with k random bits. |
token_bytes() | Return a random byte string with n bytes. |
token_hex() | Return a random hexadecimal string with n bytes. |
token_urlsafe() | Return a URL-safe random string with n bytes. |