Start learning free

LESSON 26 OF 56 · SECURITY: CRYPTOGRAPHY FOR DEVELOPERS

Codes Nobody Can Guess in Python

Practice

Newsletter subscribers get a coupon code worth 10% off. A code works once, for whoever types it first at checkout. The shop used to build codes with Python's random module, seeded with the time the server started. The attack: Mallory subscribes, gets her own code, and tries every second of the last hour as the seed until one makes exactly her code. The next code from that seed is the one Ana got, so Mallory spends Ana's discount before Ana does.

Why random fails: it is a pseudo-random generator, a formula that turns a seed into numbers that only look random. The same seed always gives the same numbers. That's what you want for a simulation or a game you can replay, and exactly what you don't want for a secret:

import random
random.seed(42)
print(random.randint(1, 6))   # the same number on every run

Use secrets instead: it takes its randomness from the operating system, so there is no seed to guess, and one code says nothing about the next. secrets.choice(["red", "green", "blue"]) picks one item, and secrets.token_urlsafe(16) makes a long random token in one call. People type coupon codes by hand, so here you pick 10 characters from a 32-character alphabet that leaves out 0, O, 1 and I. That makes about 1015 possible codes.

Right now new_code returns "", so every subscriber gets the same empty code. /check/guess is the check playing Mallory. It tries every seed of the last hour, answers the code that would come after hers, and says whether your code called random at all.

POST /newsletter  {"email": "mallory@example.com"}  →  201  {"coupon": "<mine>", "email": "mallory@example.com"}
POST /newsletter  {"email": "ana@example.com"}      →  201  {"coupon": "<ana>", "email": "ana@example.com"}
POST /check/guess {"code": "<mine>"}               →  200  {"guess": null, "used_random": false}
POST /checkout    the check's guess                 →  400  {"error": "Unknown coupon"}
POST /checkout    {"coupon": "<ana>"}              →  200  {"discount_percent": 10}
POST /checkout    {"coupon": "<ana>"}              →  400  {"error": "Unknown coupon"}

Your task: set ALPHABET to "ABCDEFGHJKLMNPQRSTUVWXYZ23456789". Then make new_code build a 10-character code, adding one character picked by secrets.choice from ALPHABET in each round. Use nothing from random.


Assignment
Follow the Coding Tutorial to build coupon codes from secrets, so that one code tells nobody the next.


Hint
A for loop over range(10) adds one character to code in each round. random is for simulations. Anything that must stay secret comes from secrets.


STEP 1 OF 3
    Ctrl + Enter to check

    Secx Secrets Random in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free