Sub topic 9
When not to use random: passwords and tokens
The random module is built for speed and repeatability, not secrecy. This chapter explains why that makes it unsafe for passwords, session tokens, and similar values. It also shows how to use the secrets module instead.
It assumes you have read the earlier chapters on random and seeding. You should be comfortable with random.choice, random.Random(seed), and calling a function from an imported module.
Why random is predictable
Python's random module uses a pseudo-random number generator (PRNG) called the Mersenne Twister. A PRNG is a deterministic algorithm. It holds an internal state, and each call transforms that state and returns a number derived from it. The output looks random, but the same state always produces the same sequence.
You already used this property when you seeded a generator. Seeding is useful for tests and simulations. For security it is a weakness, because anyone who learns the state can compute every future value.
The following code shows that a second generator with a copied state produces identical output:
import random
a = random.Random()
b = random.Random()
b.setstate(a.getstate()) # copy the internal state
print([a.getrandbits(32) for _ in range(3)] == [b.getrandbits(32) for _ in range(3)]) # TrueAn attacker usually cannot read your generator's state directly. The Mersenne Twister has a different problem. Its state is 624 32-bit words, and each output is a reversible transformation of part of that state. If an attacker sees 624 consecutive 32-bit outputs, they can rebuild the state and predict everything that follows. Public tools exist that automate this. Suppose your service issues "random" password-reset tokens from random, and an attacker can request enough of them. They can then predict the token you will issue to someone else.
Common ways this goes wrong
- Predictable seeds. Calling
random.seed(int(time.time()))leaves only a few thousand plausible seeds. An attacker who knows roughly when a token was made can try them all. - Shared global state. The module-level functions such as
random.randintall use one hidden generator. Any other code in the process can reseed it or consume values from it. - Leaked outputs. Anything you show a user, such as order numbers, coupon codes, or request IDs, gives an observer more outputs to analyze.
- Small output spaces. A value like
random.randint(1000, 9999)has only 9000 possibilities. This is a problem even with a perfect generator, because an attacker can guess them all.
The secrets module
The secrets module draws randomness from the operating system's cryptographically secure source (for example /dev/urandom on Linux or the Windows CryptoAPI). These sources collect unpredictable events from hardware and the system. They are designed so that observing past output tells you nothing about future output. There is no seed and no state you can copy.
| Function | Returns | Typical use |
|---|---|---|
| `secrets.token_bytes(n)` | `n` random bytes | Encryption keys, salts |
| `secrets.token_hex(n)` | hex string of `2 * n` characters | API keys, file names |
| `secrets.token_urlsafe(n)` | URL-safe text from `n` random bytes | Reset links, session IDs |
| `secrets.choice(seq)` | one element of `seq` | Passwords from an alphabet |
| `secrets.randbelow(n)` | integer from `0` to `n - 1` | Numeric codes |
| `secrets.randbits(k)` | integer with `k` random bits | Large random integers |
| `secrets.compare_digest(a, b)` | `True` or `False` | Comparing secrets safely |
The n in the three token functions counts bytes of randomness, not characters of output. The output length differs, as the code below shows:
import secrets
print(len(secrets.token_bytes(16))) # 16
print(len(secrets.token_hex(16))) # 32
print(len(secrets.token_urlsafe(16))) # 22token_urlsafe encodes bytes with Base64 using only URL-safe characters (letters, digits, -, and _). Sixteen bytes become 22 characters. If you leave out n, each function uses a default length that Python considers reasonable. That default can change between versions, so choose a length explicitly when a system depends on it.
Generating passwords
Use secrets.choice the way you used random.choice, but with a secure source. Join the picks into a string:
import secrets
import string
ALPHABET = string.ascii_letters + string.digits
def make_password(length=16):
return "".join(secrets.choice(ALPHABET) for _ in range(length))
print(len(make_password())) # 16Many sites require at least one lowercase letter, one uppercase letter, and one digit. A common approach is to generate a password and retry until it passes the check. Because every candidate is drawn uniformly, retrying does not weaken the result in a way that matters:
import secrets
import string
ALPHABET = string.ascii_letters + string.digits
def make_strong_password(length=16):
while True:
password = "".join(secrets.choice(ALPHABET) for _ in range(length))
if (any(c.islower() for c in password)
and any(c.isupper() for c in password)
and any(c.isdigit() for c in password)):
return password
pw = make_strong_password()
print(len(pw), any(c.isdigit() for c in pw)) # 16 TrueEstimating strength
The strength of a password is measured in bits of entropy. For a password of L characters chosen uniformly from an alphabet of N characters, the entropy is L * log2(N). You can compute it with the math module:
import math
alphabet_size = 62 # 26 + 26 + 10
length = 16
print(round(length * math.log2(alphabet_size), 1)) # 95.3Each extra bit doubles the number of guesses an attacker needs. About 95 bits is far beyond what brute force can reach. Compare that with the four-digit code mentioned earlier. Its alphabet has 10 symbols and its length is 4, so it has about 13.3 bits, or 10,000 possibilities. No generator can make such a short code safe against guessing. For those cases you need rate limiting and expiry as well.
Numeric codes
One-time codes sent by text message need leading zeros preserved. Format the integer instead of converting it to a string by hand:
import secrets
code = f"{secrets.randbelow(10**6):06d}"
print(len(code)) # 6randbelow(10**6) returns a value from 0 to 999999, each equally likely. The 06d format pads it to six digits.
Comparing secrets safely
An ordinary == on strings stops at the first character that differs. In principle, an attacker who can measure response times very precisely can use this to learn a secret one character at a time. This is called a timing attack. secrets.compare_digest takes time that does not depend on where the values differ:
import secrets
stored = secrets.token_hex(16)
supplied = stored # pretend this arrived in a request
print(secrets.compare_digest(stored, supplied)) # TrueBoth arguments must be the same type: either both bytes, or both str containing only ASCII characters. A str with non-ASCII characters raises TypeError, so encode to bytes first if your data may contain them.
SystemRandom: secure sources with the random API
Sometimes you need a method that secrets does not offer, such as shuffle or sample. random.SystemRandom has the same interface as random.Random but reads from the operating system's secure source:
import random
sysrand = random.SystemRandom()
cards = list(range(1, 11))
sysrand.shuffle(cards)
print(sorted(cards) == list(range(1, 11))) # True: same cards, new order
print(len(sysrand.sample(cards, k=3))) # 3Two properties follow from its design. Calling seed() on a SystemRandom has no effect, and getstate() and setstate() raise NotImplementedError. So a SystemRandom result can never be reproduced. That is the point for security, and the reason it is unsuitable for tests that need repeatable output.
Choosing the right tool
Use these rules in practice:
- Use
secretsfor passwords, tokens, reset links, session IDs, API keys, salts, and one-time codes. - Use
randomfor games, simulations, sampling test data, shuffling a playlist, and anything else where a predictable value costs nothing. - Use a seeded
random.Random(seed)when you need to reproduce a run exactly. - Never seed a generator that produces secrets.
- Never log a secret, and never put a token in a place where
randomoutput is also shown, because mixing them does not make therandomvalues safer.
Common mistakes
- Building a token with
"".join(random.choice(chars) for _ in range(32)). It looks long, but the output stream is predictable. Replacerandom.choicewithsecrets.choice. - Using
uuid.uuid4()as a secret and assuming it is arbitrarily strong. It does use the OS source, but it carries only 122 random bits and its format is public.secrets.token_urlsafeis clearer about intent. - Hashing a timestamp or counter and calling the result a token. A hash is deterministic, so anyone who guesses the input can compute the token.
- Comparing tokens with
==instead ofsecrets.compare_digest.
Exercise
A teammate writes token = "".join(random.choice(string.ascii_letters) for _ in range(40)) to create password-reset tokens. Name two things wrong with it and give a corrected version.
Show answer
The random module is a predictable PRNG, so an attacker who observes enough outputs can predict future tokens, and the code may also be seeded with a guessable value. Also, the alphabet has only 52 characters and no digits, which is less than ideal, though 40 characters is still plenty of length. The main fix is to use secrets, for example token = secrets.token_urlsafe(32). Alternatively, "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(40)) keeps the same structure.
Exercise
Write a function otp() that returns a six-digit one-time code as a string, with leading zeros kept, using a secure source. What would be the entropy in bits, to one decimal place, using math.log2?
Show answer
import secrets then def otp(): return f"{secrets.randbelow(10**6):06d}". There are 106 possible codes, so the entropy is `math.log2(106)`, which is about 19.9 bits. That is small, so the code must also expire quickly and limit the number of attempts.