Start learning free

LESSON 27 OF 56 · SECURITY: CRYPTOGRAPHY FOR DEVELOPERS

Rotate the Signing Key in Python

Practice

The shop's login tokens are signed with an HMAC key named k1, and that key has leaked. Anyone who holds it can sign a token for any customer, with an expiry years away, and today's /me answers 200 with that customer's account.

Rotating the key: a new key, k2, signs every new token. You can't just delete k1: whoever logged in shortly before the switch holds an honest k1 token for up to TOKEN_SECONDS more. So every token starts with a key id (kid), as kid.payload.signature. The server checks each token with the key it names, and keeps k1 only until its last honest token has expired.

The kid is written by whoever made the token, so treat it like any other input: it can name a key you no longer hold, or one that never existed. Here is the same idea for webhooks that name their key in a header:

WEBHOOK_KEYS = {"2025": b"old-secret", "2026": b"new-secret"}

@app.post("/webhooks/payment")
def payment_webhook():
    key = WEBHOOK_KEYS.get(request.headers.get("X-Key-Id", ""))
    if key is None:
        return jsonify({"error": "Unknown key"}), 401
    ...

The check signs its own tokens with the keys k0 (retired long ago), k1 (leaked) and k2, and sets the clock with an X-Test-Clock header. The switch to k2 happened at 1800000000:

GET /me      (Ana's k1 token, clock 1800000100)           →  200  {"email": "ana@example.com", "exp": 1800000600}
POST /login  {"email": "ana@example.com", …}, clock 1800000100  →  200  {"token": "k2.…"}
GET /me      (that new token, clock 1800000950)           →  200  {"email": "ana@example.com", "exp": 1800001000}
GET /me      (forged k1 token for Ben, clock 1800000950)  →  401  {"error": "Login required"}
GET /me      (a token with kid k0)                        →  401  {"error": "Login required"}
GET /me      (kid k2, signed with the k1 key)             →  401  {"error": "Login required"}

Your task: add k2 to KEYS, sign new tokens with it and put its key id in front. Then make read_token refuse a kid the server doesn't hold, and refuse k1 from 1800000000 + TOKEN_SECONDS on.


Assignment
Follow the Coding Tutorial to add the new signing key, put the key id in every new token, and make read_token refuse unknown keys and the old key once its time is up.


Hint
The kid comes from the visitor: check it with in before you use KEYS[kid]. The old key's end time is the switch plus the longest a token can live; after that, only a forger still needs it.


STEP 1 OF 8
    Ctrl + Enter to check

    Secx Key Rotation 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