---
title: "Lab: Storing passwords and building TOTP codes"
domain: cybersecurity
level: beginner
duration: "45 min"
cost: "free"
environment: "your own computer (Linux, macOS, or Windows with WSL2) with Python 3.9 or later; an authenticator app on your phone is optional"
---

# Lab: Storing passwords and building TOTP codes

## Goal
See with your own eyes why a plain hash is a bad way to store passwords, store passwords the safe way with a salt and a slow hash, and build the six-digit code of an authenticator app yourself in about 20 lines of Python. You then check your code against the official test values of RFC 6238.

## Objectives
- Show that a plain SHA-256 hash gives the same value for the same password, and that a common password can be looked up.
- Store passwords with a random salt and `hashlib.scrypt`, and verify them with a constant-time comparison.
- Generate TOTP codes and check them against the RFC 6238 Appendix B test vectors.
- Say which second factor would stop a phishing site that relays codes in real time.

## Prerequisites
- Python 3.9 or later (`python3 --version`). You paste short scripts and run them; you don't need to be a programmer.
- A terminal and a place to paste text (the commands below create the files for you).
- Optional (step 4): an authenticator app on your phone that can add an account by typing a key (most can).
- [The Authentication and MFA lesson](lesson.md) of this module.
- No accounts, no network and no payment details.

> [!WARNING]
> Everything here runs on your own computer with invented users and passwords. Never use a password you really use, and never paste a real account's TOTP secret into any script. The secret you create in step 4 is **for this lab only**: remove it from your phone app in the Cleanup section.

## Architecture
![Left, a zone for your computer, folder ~/auth-lab, with four steps: step 1 plain_hash.py shows the same password giving the same SHA-256; step 2 store.py stores with a salt and scrypt so values differ; step 3 totp.py checks the RFC 6238 test vectors; step 4 show_code.py prints a random secret and a live code. Right, an optional phone zone with an authenticator app where you type the lab secret by hand. An arrow joins step 4 to the app and you compare whether both show the same six digits. A note says to remove the secret from the phone at cleanup.](../../../assets/diagrams/auth-lab-architecture.svg)

*Figure 1. Four small scripts in one folder. Only step 4 touches your phone, and only if you want it to.*

## Steps

### Step 1 — See why plain hashes are bad (8 min)
A hash turns a password into a fixed-length fingerprint that can't be reversed. Storing `SHA-256(password)` sounds safe. Let's see what an attacker who steals such a table can do. Create the folder and a script:

```bash
mkdir ~/auth-lab
cd ~/auth-lab
cat > plain_hash.py <<'EOF2'
import hashlib

def sha256(text):
    return hashlib.sha256(text.encode()).hexdigest()

# A pretend user table where passwords are stored as a plain SHA-256 hash.
users = {"alice": sha256("sunshine1"), "bob": sha256("sunshine1"), "carol": sha256("c0rrect horse battery")}
for name, stored in users.items():
    print(name, stored)

# An attacker who stole the table tries a short list of common passwords.
common = ["123456", "password", "qwerty", "letmein", "sunshine1"]
lookup = {sha256(word): word for word in common}
print()
for name, stored in users.items():
    print(name, "->", lookup.get(stored, "not in my list"))
EOF2
python3 plain_hash.py
```

Expected output:
```text
alice 284fff3bd254b48cca05a8bfc4fad69e05cad0d086513a034a66a118829e6fa4
bob 284fff3bd254b48cca05a8bfc4fad69e05cad0d086513a034a66a118829e6fa4
carol af2de743ce77cb99a82cda058f8a04c158bf7f8109e06f302539ba2107320f8d

alice -> sunshine1
bob -> sunshine1
carol -> not in my list
```

In plain words:

- **alice and bob have the same stored value.** Same password gives the same hash. Anyone reading the table sees that two people share a password, and cracking one cracks both.
- **The second half is the attacker.** They hash each common password once, build a lookup table, and compare it with the stolen table. Alice and bob fall in one lookup. Real lists have billions of entries, and fast hashes like SHA-256 let a graphics card test billions per second.
- **carol is safe only because her passphrase isn't on the list.** That is luck, not design.

<details>
<summary>Why not simply hash it twice?</summary>

Hashing twice with the same fast function is still fast, and still gives the same value for the same password. The two fixes are a **salt** (different value per user) and a **slow** hash (expensive per guess). Step 2 uses both.

</details>

### Step 2 — Store passwords with a salt and scrypt (10 min)
Now the right way. For each user, create a random **salt**, then hash the password and the salt together with **scrypt**, a deliberately slow, memory-hungry function. Store the salt next to the result. To log in, repeat the calculation with the stored salt and compare.

```bash
cat > store.py <<'EOF2'
import hashlib, hmac, os

def make_record(password):
    salt = os.urandom(16)  # random, different for every user
    digest = hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)
    return salt, digest

def check(password, salt, digest):
    attempt = hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)
    return hmac.compare_digest(attempt, digest)

alice = make_record("sunshine1")
bob = make_record("sunshine1")
print("alice salt:  ", alice[0].hex())
print("alice stored:", alice[1].hex())
print("bob salt:    ", bob[0].hex())
print("bob stored:  ", bob[1].hex())
print("same stored value?", alice[1] == bob[1])
print("alice, right password:", check("sunshine1", *alice))
print("alice, wrong password:", check("sunshine2", *alice))
EOF2
python3 store.py
```

Expected output (the hex values are random and **change every run**; the last three lines never change):
```text
alice salt:   193e9e110d6fa0c36ea40a17ebd745be
alice stored: a58c567800dd4b22ff91e798bf0d25af061a5bbb06988decd854e812ea7d7729
bob salt:     ecca3df25d21df01104b2ad8b5795727
bob stored:   a7e5da3f8effd62fda91f6dabfeadafe9511c49457f9a28ef35761d10a5b750c
same stored value? False
alice, right password: True
alice, wrong password: False
```

In plain words:

- **alice and bob use the same password, but the stored values differ.** Their salts are different, so the hashes are different. A lookup table made in advance is useless, and the attacker must attack each account separately.
- **The salt is stored in the clear.** That's fine: its job is to be unique, not secret.
- **Checking** repeats scrypt with the saved salt. `True` for the right password, `False` for the wrong one.
- **`hmac.compare_digest`** compares two values in constant time. A normal `==` can stop at the first different byte, and that tiny timing difference can leak information.
- **Slow on purpose.** One scrypt takes a few hundredths of a second here. Nobody notices at login, but for an attacker it multiplies the cost of every single guess.

> [!NOTE]
> `n=2**14` is chosen so the lab runs fast on any computer. Real systems use stronger settings, or Argon2id. Look up the current recommendations in the OWASP Password Storage Cheat Sheet instead of copying numbers from a lab.

Run it a second time and look at the salts:

```bash
python3 store.py | head -2
```

The salt and stored value are different again, even though the password hasn't changed.

### Step 3 — Build TOTP and check it against the RFC (12 min)
A TOTP code is a calculation on a shared secret and the time. You'll write it as a small module that later steps reuse. Read the comments: each line is one box of the figure in the lesson.

```bash
cat > totp.py <<'EOF2'
import hashlib, hmac, struct, time

def totp(secret_bytes, t=None, digits=6, step=30):
    counter = int((time.time() if t is None else t) // step)  # the time step T
    mac = hmac.new(secret_bytes, struct.pack(">Q", counter), hashlib.sha1).digest()
    offset = mac[-1] & 0x0F                                   # dynamic truncation
    number = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
    return str(number % 10**digits).zfill(digits)

if __name__ == "__main__":
    secret = b"12345678901234567890"   # RFC 6238 test secret
    for t, expected in [(59, "94287082"), (1111111109, "07081804"), (1111111111, "14050471"),
                        (1234567890, "89005924"), (2000000000, "69279037")]:
        code = totp(secret, t, digits=8)
        print(t, code, expected, "OK" if code == expected else "WRONG")
EOF2
python3 totp.py
```

Expected output:
```text
59 94287082 94287082 OK
1111111109 07081804 07081804 OK
1111111111 14050471 14050471 OK
1234567890 89005924 89005924 OK
2000000000 69279037 69279037 OK
```

In plain words:

- **Each line** gives a Unix time in seconds, the code your function computed, the code the RFC says is right, and OK or WRONG.
- The five test times and expected 8-digit codes come from **RFC 6238, Appendix B** (the SHA-1 column). Getting five OK lines means your code does exactly what authenticator apps do.
- The function's lines map to the lesson: `// step` is the time step, `hmac.new(...)` is the HMAC-SHA1, `& 0x0F` and the slice are the dynamic truncation, `% 10**digits` gives the digits.
- Real apps use 6 digits, which is the default (`digits=6`); the RFC vectors use 8.

Quick check: the first line is time 59, which is 59 seconds after 1 January 1970. Time step `59 // 30` is 1. What 6-digit code would an app show then?

<details>
<summary>Show the answer</summary>

The last six digits of the 8-digit value: `287082`. You can check:

```bash
python3 -c "from totp import totp; print(totp(b'12345678901234567890', 59))"
```

Output: `287082`. (The 6-digit code is the same number modulo a million, so it's the last six digits of `94287082`.)

</details>

### Step 4 — A real secret and a live code (10 min)
Authenticator apps keep the secret as text in **base32** (letters A-Z and digits 2-7). Let's make a random one, and print the current code every five seconds.

```bash
cat > show_code.py <<'EOF2'
import base64, secrets, time
from totp import totp

secret_b32 = base64.b32encode(secrets.token_bytes(10)).decode()  # 80 random bits -> 16 letters
print("Secret (lab only):", secret_b32)
key = base64.b32decode(secret_b32)
for _ in range(6):
    left = 30 - int(time.time()) % 30
    print(time.strftime("%H:%M:%S"), totp(key), f"(changes in {left}s)")
    time.sleep(5)
EOF2
python3 show_code.py
```

Expected output (the secret, the times and the codes **are different for you**; the shape is the same):
```text
Secret (lab only): EM35V2C6LLWLHA47
20:35:52 297598 (changes in 8s)
20:35:57 297598 (changes in 3s)
20:36:02 434430 (changes in 28s)
20:36:07 434430 (changes in 23s)
20:36:12 434430 (changes in 18s)
20:36:17 434430 (changes in 13s)
```

In plain words: the code stays the same for 30 seconds (the same time step), then changes. The "changes in" counter reaches zero when the next step starts. The server and your phone follow the same clock, so they agree without talking to each other.

**Optional: compare with your phone.** Run the script again, so the secret stays on your screen, and in your authenticator app choose "add an account" and then "enter a setup key" (the wording differs by app):

1. Account name: `auth-lab`.
2. Key: the 16 letters printed after `Secret (lab only):`.
3. Type of key: **time-based**. Leave the defaults (6 digits, 30 seconds, SHA-1).

Compare the six digits in the app with the ones in the terminal. They should match. If the phone shows a code just before a change and the terminal a moment after, wait for the next one.

You've just done what scanning a QR code does: a QR code is only this secret, plus a name, written as an `otpauth://` link in picture form.

### Step 5 — Thinking exercise: who stops the relay? (5 min)
A phishing site shows a copy of your company's login page. You type your password and the six-digit code from your app. In the background, the site sends both to the real site within seconds and gets logged in as you.

Question: for each method, would it stop this attack? Answer yes or no and say why: (a) a password alone, (b) an SMS code, (c) the TOTP code you just built, (d) a push notification with number matching, (e) a FIDO2 security key or passkey.

<details>
<summary>Show the answer</summary>

| Method | Stops real-time relay? | Why |
|---|---|---|
| (a) Password alone | No | The phishing page collects it directly. |
| (b) SMS code | No | You type the code into the fake page, which relays it. |
| (c) TOTP code | No | The code is valid for 30 seconds and isn't tied to a website. Your script proves it: the function takes only a secret and a time, never a web address. |
| (d) Push with number matching | Partly | It's harder, because the user must match the number shown on the real login. But a relay can still show that number on the fake page, so a tired or rushed user can be fooled. |
| (e) FIDO2 key or passkey | **Yes** | The key signs a challenge together with the web address the browser sees. On the fake site there's no matching credential, and a signature for the fake address is useless on the real site. |

That's why guidance now favors phishing-resistant methods for administrators and high-value accounts.

</details>

## Verification
Check these, in order:

```bash
cd ~/auth-lab
python3 totp.py
python3 store.py | tail -3
```

You pass if:
- `totp.py` prints five lines that all end in `OK`.
- `store.py` prints `same stored value? False`, then `True` for the right password and `False` for the wrong one.
- In step 1, alice and bob showed the same SHA-256 and a lookup recovered `sunshine1`.
- (Optional) Your phone and `show_code.py` showed the same six digits.

## Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| `AttributeError: module 'hashlib' has no attribute 'scrypt'` | This Python was built without OpenSSL scrypt support | Use a standard Python 3.9 or later from your system or python.org; on a minimal container install the full `python3` package |
| `ModuleNotFoundError: No module named 'totp'` | You aren't in `~/auth-lab`, or `totp.py` is missing or renamed | Run `cd ~/auth-lab`, check `ls`, and re-run the step 3 block |
| `SyntaxError` or `IndentationError` | The paste lost some lines or spaces | Delete that file and paste the whole block again, including the last `EOF2` line |
| `totp.py` prints `WRONG` | A typo in the code, in an RFC value or the secret | Compare the file with the block; the secret must be exactly `12345678901234567890` |
| The phone shows a different code | Typo in the secret; the app isn't set to time-based; the phone clock is off by more than a few seconds | Re-enter the key, check the type is time-based, turn on automatic date and time on the phone |
| `mkdir: cannot create directory ... File exists` | You already ran step 1 | Fine: run `cd ~/auth-lab` and continue |

## Challenge (optional)
1. Write `verify(secret, code)` that accepts the code for the current step and the steps just before and after (a one-step window, like a real server). Test it by passing the code from 30 seconds ago, and the code from 90 seconds ago.
2. Time `make_record` with `n=2**14` and with `n=2**17` (for the bigger value, add `maxmem=2**28` to the `hashlib.scrypt` call, or Python refuses to use that much memory). How much slower does one password check become? What does that mean for an attacker?
3. Put a long passphrase through `check` with and without one character changed. Does the stored value look similar? Why not?

## Cleanup
Remove the folder, and the lab secret from your phone:

```bash
cd ~
rm -r ~/auth-lab
```

On your phone, open the authenticator app and delete the `auth-lab` account if you added it. Nothing else was installed or changed.

## What you learned
- A plain hash gives the same value for the same password and can be looked up, so it is not safe password storage.
- A random salt per user and a slow hash such as scrypt make identical passwords look different and every guess expensive. Compare in constant time.
- A TOTP code is just HMAC-SHA1 of the 30-second time step with a shared secret, truncated to digits. You checked it against RFC 6238.
- A code you type isn't tied to a website, so a phishing site can relay it. A FIDO2 key or passkey signs the origin, so it can't be relayed.
