Course contentsShow
← Python
Lesson 695 of 1,06011. Standard Library EssentialsFree lesson

Generating Cryptographically Secure Tokens with the Secrets Module

Create secure random tokens using secrets.token_hex and token_urlsafe, understanding why standard random modules are unsuitable for security.

In this lesson, you will learn how to generate cryptographically strong random tokens using the secrets module to secure sensitive application data.

Why random is not enough

Previously, we explored the random module for tasks like shuffling sequences or picking random numbers. While excellent for simulations and games, random is pseudo-random. It uses a deterministic algorithm that, if an attacker guesses your seed, allows them to predict every subsequent number generated. For security-critical tasks—like creating password reset tokens, session IDs, or API keys—this predictability is a major vulnerability.

The secrets module

The secrets module is designed specifically for cryptography. It uses the most secure source of randomness provided by your operating system, making the output practically impossible to predict.

Creating Secure Tokens

You can generate tokens in various formats depending on your needs:

import secrets

# Generate a hexadecimal string (often used for internal IDs)
hex_token = secrets.token_hex(16)
print(f"Hex Token: {hex_token}")

# Generate a URL-safe text string (ideal for web links)
url_token = secrets.token_urlsafe(16)
print(f"URL Token: {url_token}")
  • secrets.token_hex(nbytes) returns a string of hexadecimal digits. Each byte is converted to two hex digits, so nbytes=16 results in a 32-character string.
  • secrets.token_urlsafe(nbytes) returns a URL-safe Base64 string. This is safer for web contexts as it avoids characters that might break URL parsing (like + or /).

Best Practices

When using these functions, the nbytes argument defines the entropy (the randomness). A higher number of bytes results in a longer, more secure token. A common standard for tokens is 16 to 32 bytes, which provides sufficient complexity to prevent brute-force attacks while remaining manageable for storage in your database.

By switching from random to secrets, you ensure that your security tokens remain secret and unpredictable, effectively shielding your application from session hijacking or token prediction attacks.

Key Takeaway: Always use the secrets module instead of random for security-sensitive tokens, as it leverages cryptographically secure system entropy to ensure your generated values are truly unpredictable.