python · level 3 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Use , not random, for anything that must stay secret.
random is built for games and simulations. Its numbers follow a hidden pattern, so with enough samples an attacker can predict the next one. Never use it for a password, a or a sign-in code.
The secrets module asks the operating system for values nobody can predict. token_hex(16) gives 32 characters from 0 to 9 and a to f, token_urlsafe(16) gives a token safe to put in a link, and choice picks from a list.
Check a secret with secrets.compare_digest(a, b). A plain == stops at the first wrong character, so its speed can leak how much of a guess was right. That is a .
import secrets
import string
reset_token = secrets.token_urlsafe(16)
print("Reset link: https://example.com/reset?token=" + reset_token)
alphabet = string.ascii_uppercase + string.digits
code = "".join(secrets.choice(alphabet) for n in range(6))
print("Your sign-in code is", code)
print(secrets.compare_digest(code, code)) Your output differs from everyone else's, and from your own next run, which is the whole point.
guess first
Same seed, twice. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import random
random.seed(2024)
first = [random.randint(1, 99) for n in range(3)]
random.seed(2024)
second = [random.randint(1, 99) for n in range(3)]
print(first == second)
your turn
Your turn. Make a sign-in code.
Fill the first blank with the secrets function that picks one item at random. Pick a code length between 4 and 8 for the second.
fix it
The key must be exactly 16 characters. Fix it!
- Look at the length printed after the key. Is it the 16 you asked for?
- The number is how many random bytes to use, and each byte becomes two characters.
- Ask for 8 bytes with
secrets.token_hex(8), then run.
nailed it
your secrets are safe from guessing. :D
randomfollows a pattern.secretscannot be predicted.token_hex,token_urlsafeandchoicemake tokens and codes.- Compare secrets with
compare_digest, never with==.
new words in your collection
- token
- secrets
- timing attack
This lesson isn’t saved. A free account remembers every lesson you finish.