Why You Should Use secrets Instead of random in Python
Recently, I contributed to the lepture/captcha library by replacing Python’s random module with secrets for better security (PR #79).
The Problem
Many developers use the built-in random module for generating random numbers, but it’s not cryptographically secure. It’s great for simulations and non-security-critical applications, but not for things like:
?? CAPTCHA generation
?? API keys or tokens
??Passwords
The Secure Alternative: secrets
PEP 506 introduced the secrets module, which is designed for cryptographic randomness. It uses secure system sources (like /dev/urandom on Linux or CryptGenRandom on Windows), making it the right choice for security-sensitive tasks.
Example: Switching from random to secrets
Here’s a simple change I made in the PR:
? Insecure (random)
import random
token = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=16))
? Secure (secrets)
import secrets
token = ''.join(secrets.choice('abcdefghijklmnopqrstuvwxyz0123456789') for _ in range(16))
Takeaway
If your code involves security-sensitive randomness, always use secrets instead of random. It’s a small change but makes a big difference!
Would love to hear your thoughts—have you encountered similar security issues in Python projects? ??