Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 03 · 60 minutes

Store passwords safely and build a one-time code generator

After this lesson you can
  • Tell identification from authentication and name the three factor types
  • Hash a password with a salt and verify it in constant time
  • Build a TOTP generator and check it against the RFC 6238 test vector
Lab files of this lesson (6)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A friend runs a small web shop and asks you to look at the login code. You find two things: the shop stores the password of each customer as a plain SHA-256 hash, and the admin login asks for nothing but a password. Your friend says: "Show me what better looks like." You will write the safe password storage and a one-time code generator, and prove with fixed test values that both work.

Recall

Lesson 1: you add a second factor to the email account, and its likelihood falls from 4 to 1. What is the new risk number if the impact is 5?

1 x 5 = 5. The control lowers the likelihood and so the risk. The rest is residual risk.

Lesson 2: a stolen file of password hashes is an attack on which of the three goals?

Confidentiality. The secret data (the passwords that the hashes protect) reaches the wrong reader. A good hash makes the stolen file hard to use.

The idea

Identification is a claim: "I am alice". Authentication is the proof of that claim. A system that accepts the claim without proof does not authenticate.

A proof comes from one or more factors:

FactorWhat it isExample
KnowledgeSomething you knowPassword, PIN
PossessionSomething you havePhone, hardware key
InherenceSomething you areFingerprint, face

Multi-factor authentication (MFA) uses factors of different types. Two passwords are one factor twice.

A server must never keep passwords. It keeps a hash: a one-way result that cannot be turned back into the password. Two details make this safe:

  • A salt is a random value, unique for each user, stored beside the hash. Two users with the same password get different hashes, and an attacker cannot use one table of precomputed hashes against all of them.
  • The hash must be slow. A fast hash such as SHA-256 lets an attacker try billions of guesses a second. A password-hashing function such as scrypt is built to cost time and memory for every guess.

This is the check that runs at every login:

The login check
UserApplicationPassword storename and passwordread the salt and hash of the namesalt and stored hashscrypt(password, salt)compare in constant timesigned in, or deniedUserApplicationPasswordstore123456
  1. User → Application: name and password
  2. Application → Password store: read the salt and hash of the name
  3. Password store → Application: salt and stored hash
  4. Application: scrypt(password, salt)
  5. Application: compare in constant time
  6. Application → User: signed in, or denied

A TOTP (time-based one-time password, RFC 6238) is a code that both sides compute from a shared secret and the time. The server never sends it, so there is nothing to intercept in advance.

Worked example

1. Write the password code

Write password.py in ~/krlab/security-basics. Five things in it are new:

  • password.encode() turns text into bytes, which the hash functions need. salt or os.urandom(16) uses the salt that you pass in, and makes a new one when you pass none.
  • os.urandom(16) gives 16 random bytes from the operating system. They are the salt.
  • hashlib.scrypt is the slow hash. n sets how much time and memory one guess costs, r and p tune its inner work, and dklen is the length of the result in bytes.
  • hmac.compare_digest compares two values in constant time, so the time of the check does not leak how many bytes were right.
  • The line if __name__ == "__main__": starts a block that runs only when you run the file yourself, and not when another program imports it. You will import this file in your turn.

password.py

import hashlib
import hmac
import os
import time


def hash_password(password, salt=None):
    salt = salt or os.urandom(16)
    key = hashlib.scrypt(password.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)
    return salt, key


def verify(password, salt, key):
    _, candidate = hash_password(password, salt)
    return hmac.compare_digest(candidate, key)


if __name__ == "__main__":
    salt1, key1 = hash_password("correct horse")
    salt2, key2 = hash_password("correct horse")
    print("salt 1:", salt1.hex())
    print("hash 1:", key1.hex())
    print("hash 2:", key2.hex())
    print("same hash for the same password?", key1 == key2)

    print("right password:", verify("correct horse", salt1, key1))
    print("wrong password:", verify("battery staple", salt1, key1))

    start = time.perf_counter()
    verify("correct horse", salt1, key1)
    print(f"one check takes {(time.perf_counter() - start) * 1000:.0f} ms")

2. Run it

python3 runs a Python file. .hex() shows bytes as hex characters, and time.perf_counter() is a precise clock for timing.

python3 password.py
salt 1: a4497cdfeb9df559e18ee09ab6964a23
hash 1: 5d0006ff135b84af46208ce644369f9d27de775f73ff4fce61099dee70bd9152
hash 2: 73bd9edde1c088e24b8035848cd2dfbed421cd4e8cea57f451b35b6cfeada2fd
same hash for the same password? False
right password: True
wrong password: False
one check takes 57 ms

The same password gave two different hashes, because the salts differ. Your salt and times will differ from these. In a real system you store the salt and the hash for each user.

3. Measure why slow matters

python3 -c "..." runs the Python code in the quotes, without a file. Compare the speed of a plain SHA-256 loop with scrypt on your machine.

python3 -c "
import hashlib, time
t = time.perf_counter()
for i in range(100000): hashlib.sha256(str(i).encode()).digest()
print(f'100000 SHA-256 hashes: {time.perf_counter() - t:.2f} s')
t = time.perf_counter()
for i in range(10): hashlib.scrypt(str(i).encode(), salt=b'x' * 16, n=2**14, r=8, p=1, dklen=32)
print(f'10 scrypt hashes: {time.perf_counter() - t:.2f} s')
"
100000 SHA-256 hashes: 0.27 s
10 scrypt hashes: 0.73 s

In this run that is about 370,000 guesses a second against 14 on one core. Your numbers will differ, but the gap stays at tens of thousands to one. A user waits well under a tenth of a second at login and does not notice. An attacker with a stolen database feels every millisecond. This is one core in Python. A graphics card running a hash program reaches billions of SHA-256 guesses a second, so the gap matters even more.

4. Write the TOTP code

Write totp.py. HOTP (RFC 4226) turns a counter into a short code. TOTP uses the count of 30-second steps since 1970 as the counter. HOTP works in four moves. The values below are real: they come from the RFC test secret at time 59, so the counter is 1, and the code has 8 digits.

  1. Take the HMAC of the counter. The result is 20 bytes: 75a48a19...7a2d33ab.
  2. Find an offset from the last byte. mac[-1] & 0x0F keeps the low 4 bits of that byte (& keeps the bits that are 1 in both numbers, and 0x0F is the hex way to write 00001111). The last byte is ab, so the offset is 11. An offset is always 0 to 15, so four bytes always fit.
  3. Take the four bytes from that offset: mac[11:15] is c1397eea. struct.unpack(">I", ...)[0] turns them into one number, 3241770730. & 0x7FFFFFFF clears the top bit, so that the number is positive on every system: 1094287082.
  4. Keep the last digits. % 10**8 gives 94287082. .zfill(8) adds leading zeros when the number is short, so that a code such as 07081804 keeps its zero.
The code for time 59, counter 1
75a48a19...7a2d33ab1: HMAC of the counterab2: last byte, offset 11c1397eea3: four bytes from 1110942870823: top bit cleared942870824: last 8 digits75a48a19...7a2d33ab1: HMAC of the counterab2: last byte, offset 11c1397eea3: four bytes from 1110942870823: top bit cleared942870824: last 8 digits

The RFC lists 94287082 as the right code for time 59, and step 5 checks it. Three more things are new:

  • hmac.new(key, message, hashlib.sha1) computes an HMAC: a hash that also needs a secret key.
  • struct.pack(">Q", counter) turns a number into 8 bytes in a fixed order, so that both sides feed the same bytes to the HMAC. The > means most significant byte first, Q means an 8-byte whole number, and I (in unpack) means a 4-byte one.
  • now // step is whole-number division: it counts how many full 30-second steps have passed.

totp.py

import hashlib
import hmac
import struct
import time


def hotp(key, counter, digits=6):
    mac = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
    offset = mac[-1] & 0x0F
    number = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
    return str(number % 10**digits).zfill(digits)


def totp(key, now=None, step=30, digits=6):
    now = time.time() if now is None else now
    return hotp(key, int(now // step), digits)


if __name__ == "__main__":
    key = b"12345678901234567890"  # the test secret in RFC 6238
    for when, expected in [(59, "94287082"), (1111111109, "07081804"), (1234567890, "89005924")]:
        got = totp(key, now=when, digits=8)
        print(when, got, "OK" if got == expected else "WRONG")
    print("code now:", totp(key))

5. Check it against the RFC

The RFC lists the right answer for fixed times. If your code gives the same numbers, it is correct.

python3 totp.py
59 94287082 OK
1111111109 07081804 OK
1234567890 89005924 OK
code now: 432129

The last line changes every 30 seconds. An authenticator app that holds the same secret shows the same six digits at the same time. Apps take the secret as base32 text, and base64.b32encode makes it:

python3 -c "import base64; print(base64.b32encode(b'12345678901234567890').decode())"
GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ

Most apps use the settings of totp.py (6 digits, 30 seconds, SHA-1), so an app that gets this text shows the same codes as python3 totp.py. HMAC-SHA-1 is still safe: the warning against SHA-1 in lesson 5 is for plain hashes of data. The RFC secret is for tests only: a real secret is 20 random bytes from os.urandom.

Your turn

Prove to your friend that your two files work on values that you did not see before. Use password.py and totp.py as libraries: in the lab folder, start a Python session with python3 (leave it with Ctrl+D), or write a short script, and import hash_password, verify and totp from them.

  1. Compute the TOTP of the RFC 6238 test secret 12345678901234567890 at the time 2000000000, once with 6 digits and once with 8. Compute the 8-digit code at the time 20000000000 too.
  2. Hash the password winter-2026 with scrypt, with the settings of password.py and this fixed salt: the 16 ASCII characters krlab-fixed-salt. A salt is bytes, so write it as b"krlab-fixed-salt". A fixed salt is for this test only: a real system uses a new random salt for every password.
  3. Verify the password Winter-2026 (a capital W) against that hash, and hash Winter-2026 with the same salt too.

Last, explain to your friend why the 8-digit code at time 2000000000 ends with the same six digits as the 6-digit code.

Compare with this

The % sign gives the remainder of a division. The code is the same big number, taken % 10**digits. A remainder after dividing by 108 keeps the last 8 digits of the number, and one after dividing by 106 keeps the last 6. So the 6-digit code is the last six digits of the 8-digit code: 69279037 ends in 279037.

Check yourself

A site asks for a password and then for the name of your first school. Is that MFA?

No. Both answers are knowledge factors. MFA needs factors of different types, for example a password and a code from a phone.

Why is "SHA-256(password)" a poor way to store a password?

SHA-256 is fast and has no salt, so an attacker can test billions of guesses a second and can reuse one table of hashes for all users. Use a salted, slow function such as scrypt, bcrypt or Argon2.

The salt is stored in the database in clear text. Is that a flaw?

No. The salt is not a secret. Its job is to make each hash unique so that precomputed tables are useless. The secret is the password.

A TOTP code was typed at the 29th second. Why can the check still fail?

The two clocks may differ, or the step may change before the server checks. Servers often accept the step before and the step after the current one, and they must also reject a code that they have already accepted.

Field notes

  • NIST SP 800-63B is the reference for authenticators. Revision 4 (2025) asks for at least 15 characters when the password is the only factor, and allows 8 when it is one part of MFA. It asks verifiers to allow 64 or more, a check against lists of breached passwords, and no forced periodic changes or composition rules.
  • OWASP names Argon2id first for new systems, then scrypt, then bcrypt, and gives minimum cost settings. The n=2**14 here is a teaching value: tune the cost so that a check takes some tens of milliseconds on your server, and store the parameters with each hash so that you can raise them later.
  • TOTP can still be phished: a fake site asks for the code and passes it on at once. FIDO2 and WebAuthn keys bind the proof to the real site name and resist this. RFC 6238 builds on HOTP (RFC 4226).
  • Rate-limit and lock out attempts, and log every failure. Lesson 6 uses those logs.
  • Use hmac.compare_digest for every secret comparison: tokens, API keys, MACs. An ordinary == can stop at the first byte that differs.