Python random vs secrets: why your password generator is unsafe
random is reproducible from a seed; secrets is designed to be unpredictable.
Reviewed by System Admin · Dec 2, 2026 · Editorial standards
Visual breakdown
InteractivePython random vs secrets: why your password generator is unsafe — Visual Breakdown
random module (PRNG)
- ✓Seeded internal state
- ✓Same seed gives same output
- ✓Fast, but predictable
- ✓Fine for games and simulations
secrets module (CSPRNG)
- ✓Bytes from the OS random source
- ✓No seed you can set
- ✓Output cannot be replayed
- ✓Built for passwords and tokens
The simple version
No jargonYou wrote a password generator with Python's random module. It runs, it prints a password, and it looks fine. But random is a PRNG (pseudo-random number generator). That means it produces a stream of numbers from an internal state. If someone knows or guesses that state, they can reproduce the same stream. In Python, you can set that state yourself with random.seed(). Run the same seed twice, and you get the same "random" password twice. That is the bug: your password is only as secret as the seed. The secrets module does the same job with a different promise. It pulls bytes from the operating system's cryptographic random source. You cannot set a seed. You cannot replay the stream. Two runs give different passwords, and an attacker cannot work backwards from the output to the internal state. The API looks similar: secrets.choice() picks a character, just like random.choice(). Here is a concrete example. With random.seed(42) and a fixed alphabet, two runs produce the same password. With secrets.choice() and the same alphabet, two runs produce different passwords. This is analysis of the general principle, not a claim about any specific tutorial's code. So "working" and "safe" are two different bars. Working means the function returns a string of the right length. Safe means an attacker cannot predict the next string. For a password, the second bar is the one that matters.
Why it matters in production
Implementation & syntax
import random
import secrets
import string
alphabet = string.ascii_letters + string.digits
random.seed(42)
print(''.join(random.choice(alphabet) for _ in range(12)))
random.seed(42)
print(''.join(random.choice(alphabet) for _ in range(12)))
print(''.join(secrets.choice(alphabet) for _ in range(12)))
print(''.join(secrets.choice(alphabet) for _ in range(12)))Check your understanding
Quick Concept Check
Test your understanding in 15 seconds
Why is random.seed(42) dangerous in a password generator?
Related concepts
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.