Sub topic 9
When not to use random: passwords and tokens
This chapter assumes you know random.Random, seeding, and random.choice from the previous chapters. It also assumes you can build a string from a loop or a generator expression.
Why random is predictable
The random module uses a pseudo-random number generator. It is a formula that turns an internal state into the next number. The numbers look unpredictable, but the formula is deterministic. If you know the state, you know every future value. In CPython, the generator is the Mersenne Twister. Its state can be reconstructed from a few hundred consecutive outputs.
The default seed also comes from sources an attacker may be able to narrow down. Seeding exists to make results repeatable, which is the opposite of what a secret needs.
import random
a = random.Random(42)
b = random.Random(42)
print(a.getrandbits(32) == b.getrandbits(32)) # True: same state, same outputAnyone who learns the seed or enough outputs can reproduce your "random" values. For games, simulations, and test data, that is fine. For anything an attacker benefits from guessing, it is not.
The secrets module
The secrets module draws from the operating system's cryptographically secure source. The values cannot be predicted from earlier outputs, and you cannot seed the generator.
import secrets
import string
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(16))
print(len(password)) # 16
print(len(secrets.token_hex(16))) # 32 hex characters (16 bytes)
print(len(secrets.token_urlsafe(16))) # 22 characters, safe in URLs
print(secrets.randbelow(10) in range(10)) # True: an integer from 0 to 9The functions map onto what you already know:
| Task | `random` | `secrets` |
|---|---|---|
| Pick one item | `random.choice` | `secrets.choice` |
| Integer below n | `random.randrange(n)` | `secrets.randbelow(n)` |
| Random bytes as hex | none | `secrets.token_hex(n)` |
| URL-safe token | none | `secrets.token_urlsafe(n)` |
Note that the length arguments to token_hex and token_urlsafe count bytes, not output characters. Sixteen bytes (128 bits) is a reasonable minimum for a session token or a reset link. secrets has no sample or shuffle, so build passwords by repeated secrets.choice as shown above.
Comparing secrets
Comparing a submitted token with == can stop at the first mismatching character. Response time can then leak how much of a guess was correct. Use secrets.compare_digest, which takes the same time regardless of where the values differ.
import secrets
stored = secrets.token_hex(16)
submitted = stored
print(secrets.compare_digest(stored, submitted)) # TrueCommon mistakes
- Using
random.choiceto build a password because the code looks identical to thesecretsversion. - Making tokens too short. A 4-digit code from
secrets.randbelow(10000)is secure against prediction but easy to brute-force, so limit attempts. - Seeding with the time, such as
random.seed(time.time()). Attackers can guess the time to within a small window. - Storing generated passwords in plain text.
secretscreates secrets. It does not protect them afterward.
Exercise
A teammate writes token = "".join(random.choice("0123456789abcdef") for _ in range(32)) for password reset links. Name the problem and rewrite it in one line.
Show answer
The random generator is predictable, so an attacker who observes enough outputs can predict later tokens. Use token = secrets.token_hex(16), which gives 32 hex characters from the operating system's secure source.