Secrets and tokens in Python

A secret is any value that would cause trouble in the wrong hands, and handling one well is mostly about where it lives and how you compare it. This set covers keeping a token out of your source, generating one with the secrets module, storing a hash rather than the value itself, and comparing tokens without leaking timing. The task runs the whole sequence once and asks you to read what it printed.

4 questions 1 task Read the lesson

Questions

Each one is marked as you go, and the explanation arrives straight after, which is the part worth reading.

4 questions, marked as you go.

1 Why should a token be read from the environment rather than written into the script?
2 Why use the secrets module rather than random to generate a token?
3 secrets.token_hex(16) is run. How long is the token it returns?
4 Why compare a stored token with hmac.compare_digest rather than with ==?

Tasks

These need your own device. Run the command in Termux, then paste what it printed. The marking looks at what the output means, so spacing, version numbers and ordering do not matter. If you have not installed anything yet, the lesson covers the setup.

Read, generate, hash and compare a secret

This checks whether a token is set in the environment, makes a sixteen byte hex token and confirms its length, makes a URL-safe token, hashes a fixed secret and prints the digest length, and compares two equal tokens in constant time. Paste all five lines.

Run this in Termux On your own device. Nothing on this page executes it. The command runs in your terminal, and this box only reads what you paste back.

python3 -c "import os, secrets, hashlib, hmac; print('token present:', os.environ.get('LEARMUX_DEMO_TOKEN') is not None); t = secrets.token_hex(16); print(len(t), t.isalnum()); print(len(secrets.token_urlsafe(12))); print(len(hashlib.sha256(b'local-dev-token').hexdigest())); print(hmac.compare_digest('token-abc', 'token-abc'))"
Marking your own work Both halves of this are checked in your browser, with no server involved, so nothing stops you from pasting output you did not run. The tasks are written so that the easiest way to pass one is to actually do it and read the result, which is the whole intention.

All sets Read the lesson