IntermediateLesson 6 of 127 min read

Passwords and Tokens: Hashing, Salts and Signed Sessions

Store passwords safely with a salted, slow hash, verify them in constant time, issue signed tokens that detect tampering and expiry, and cross-check the key derivation and the signature with OpenSSL.

In this lesson you will

  • Hash passwords with a salt and a slow function
  • Verify in constant time
  • Issue and verify a signed token
  • Cross-check with OpenSSL

About 28 minutes

Who is knocking?

Authentication answers the question “who are you?”. Kofi’s members log in with a password. The one rule you must never break is that the database never stores the password itself. If it is stolen, which sooner or later happens to someone, every member’s password and every site where they reused it is exposed. Instead the back end stores a hash, the result of a one-way function that is easy to compute and infeasible to reverse. A plain fast hash such as SHA-256 is not enough, because an attacker can try billions of guesses a second. A password hash such as scrypt, bcrypt or Argon2 is deliberately slow and memory-hungry, and each password gets a random salt, a unique value mixed in, so that two members with the same password have different hashes and precomputed tables are useless.

After a successful login the server must remember the member without asking for the password on every request. A common way is a signed token: the server writes a small payload, such as the member id and an expiry time, and attaches an HMAC, a keyed hash computed with a secret that only the server knows. When the token comes back, the server recomputes the HMAC. If one character of the payload was changed, the signature no longer matches, so the token cannot be forged or edited without the secret. Comparisons of secrets must use a constant-time function, hmac.compare_digest, so that the time taken does not leak how many characters matched.

Need Tool
Store a password scrypt, bcrypt or Argon2 with a random salt
Compare secrets hmac.compare_digest
Session token Random id in a database, or a signed token
Signature HMAC-SHA256 with a server secret
Never Store or log plain passwords
import hashlib, hmac, os, base64, json, time, subprocess

N, R, P = 16384, 8, 1
def hash_password(password, salt=None):
    salt = salt or os.urandom(16)
    h = hashlib.scrypt(password.encode(), salt=salt, n=N, r=R, p=P, dklen=32)
    return salt.hex() + "$" + h.hex()
def verify_password(password, stored):
    salt_hex, h_hex = stored.split("$")
    h = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt_hex), n=N, r=R, p=P, dklen=32)
    return hmac.compare_digest(h, bytes.fromhex(h_hex))

a1 = hash_password("correct horse battery")
a2 = hash_password("correct horse battery")
print("same password, two hashes differ:", a1 != a2, "| stored length:", len(a1))
print("right password:", verify_password("correct horse battery", a1), "| wrong password:", verify_password("Correct horse battery", a1))

SECRET = b"server-only-secret"
b64 = lambda b: base64.urlsafe_b64encode(b).rstrip(b"=").decode()
def make_token(member, ttl, now):
    payload = b64(json.dumps({"m": member, "exp": now + ttl}, separators=(",", ":")).encode())
    sig = b64(hmac.new(SECRET, payload.encode(), hashlib.sha256).digest())
    return payload + "." + sig
def check_token(token, now):
    try:
        payload, sig = token.split(".")
    except ValueError:
        return "malformed"
    good = b64(hmac.new(SECRET, payload.encode(), hashlib.sha256).digest())
    if not hmac.compare_digest(sig, good): return "bad signature"
    data = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
    return "expired" if data["exp"] <= now else "ok: member " + str(data["m"])

now = 1_700_000_000
tok = make_token(7, 3600, now)
forged_payload = b64(json.dumps({"m": 1, "exp": now + 3600}, separators=(",", ":")).encode())
forged = forged_payload + "." + tok.split(".")[1]
checks = {"fresh": check_token(tok, now + 10), "expired": check_token(tok, now + 4000), "forged payload": check_token(forged, now + 10), "garbage": check_token("abc", now)}
for k, v in checks.items(): print(k.ljust(15), v)
payload = tok.split(".")[0]
print("HMAC of the payload:", hmac.new(SECRET, payload.encode(), hashlib.sha256).hexdigest())
salt = bytes.fromhex(a1.split("$")[0])
ssl = subprocess.run(["openssl", "kdf", "-keylen", "32", "-binary", "-kdfopt", "pass:correct horse battery", "-kdfopt", "hexsalt:" + salt.hex(), "-kdfopt", "n:16384", "-kdfopt", "r:8", "-kdfopt", "p:1", "SCRYPT"], capture_output=True).stdout
mac = subprocess.run(["openssl", "dgst", "-sha256", "-hmac", "server-only-secret", "-hex"], input=payload, capture_output=True, text=True).stdout.split("= ")[1].strip()
print("OpenSSL scrypt matches stored hash:", ssl.hex() == a1.split("$")[1], "| OpenSSL HMAC matches:", mac == hmac.new(SECRET, payload.encode(), hashlib.sha256).hexdigest())
print("DATA " + json.dumps({"diff": a1 != a2, "len": len(a1), "checks": checks, "ssl": ssl.hex() == a1.split("$")[1], "mac": mac == hmac.new(SECRET, payload.encode(), hashlib.sha256).hexdigest()}))
same password, two hashes differ: True | stored length: 97
right password: True | wrong password: False
fresh           ok: member 7
expired         expired
forged payload  bad signature
garbage         malformed
HMAC of the payload: f6bc274bef5c380f32573097c04eea546fdbb32c562b3634630d4c252fb37111
OpenSSL scrypt matches stored hash: True | OpenSSL HMAC matches: True

Hashing the same password twice produced two different stored values (True), because each uses a fresh random 16-byte salt, which is stored with the hash as 97 characters: 32 for the salt, a separator, and 64 for the hash. Verification recomputes the hash with the stored salt and compares in constant time: the right password was accepted, and the same words with one capital letter were refused. The cost parameters N, r and p make each guess take real time and memory, a fraction of a second here, which is nothing for a member logging in and a heavy burden for an attacker trying billions of guesses. Check the current recommendations of OWASP for the cost settings, because they grow as computers get faster.

The token has two parts, the payload and the signature. Checked ten seconds after it was issued it is “ok: member 7”. Checked after its hour was over it is “expired”. The forged token swapped in a payload that claims to be member 1, an administrator, but kept the old signature, and the check returned “bad signature”, because the signature no longer matches the payload. Text that is not a token at all is “malformed”. Without the secret, nobody can create a valid signature, which is why the secret must be long, random, stored outside the code, and rotated if it leaks. Remember that the payload is only encoded, not encrypted: anyone can read it, so never put secrets in it.

Independent check: OpenSSL, a completely separate implementation, derived the scrypt hash from the same password, salt and cost settings and produced exactly the stored value (True), and computed the HMAC-SHA256 of the token payload with the same secret, which matches Python’s (True). So the hashing and signing follow the published algorithms and do not depend on one library.

Check by hand: the stored value is a 32-character hex salt (16 bytes), a dollar sign and a 64-character hex hash (32 bytes), 32 + 1 + 64 = 97 characters. The token’s expiry is the issue time plus 3,600 seconds, so a check at issue time plus 4,000 seconds is after it.

Never invent your own cryptography

Use the standard algorithms and your platform’s libraries, with parameters from a current recommendation. Mistakes in home-made schemes are subtle and are found by attackers, not by tests.

Also limit login attempts

Slow hashing helps against stolen databases, and a limit of failed attempts per account and per address helps against guessing on a live site. Return the same message for “no such user” and “wrong password”.

About this course

Every program in this lesson was run while the course was written, with Python 3.13 and only its standard library (http.server, sqlite3, hashlib, hmac), with a real server on a free local port, and cross-checked with curl, openssl or a second implementation. Tools and versions change, so check the official documentation for current behaviour. Cost parameters and recommended algorithms change with hardware, so check the current OWASP password storage guidance. Many projects use a maintained library, such as the one in their framework, instead of calling these functions directly.

Practice

Change N to 2**12 and 2**15 and measure how long one hash takes. Add a “not before” field to the token. Write a test that flips one character of a token and checks that it is refused.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What should the database store for a password?

  1. The password
  2. A fast hash without salt
  3. A salted, slow hash
  4. The password encrypted with a key in the code

Never the password itself.

What does a salt do?

  1. Speeds up hashing
  2. Makes equal passwords hash differently
  3. Encrypts the hash
  4. Shortens the hash

It defeats precomputed tables.

Why compare with hmac.compare_digest?

  1. It is shorter
  2. Constant time, so it does not leak matches
  3. It is encrypted
  4. It allows wildcards

Timing attacks.

What happens if a token’s payload is changed?

  1. The signature no longer matches
  2. Nothing
  3. It becomes encrypted
  4. It expires

Only the secret holder can sign.

Is a signed token encrypted?

  1. No, it can be read but not changed
  2. Yes
  3. Only the signature
  4. Only in HTTPS

Do not put secrets in it.

Summary

  • Never store passwords: store salted, slow hashes.
  • Compare secrets in constant time.
  • Signed tokens detect tampering and carry an expiry.
  • Cross-check cryptography with an independent tool such as OpenSSL.

Next lesson

Lesson 7 covers authorisation: who may do what.

Questions

Should I use JWT?

JSON Web Tokens are a standard format for signed tokens, and they have pitfalls, such as the algorithm choice and revocation. A random session id stored server-side is simpler for many sites. Check the current guidance for your case.

How do I let users reset a forgotten password?

Send a single-use, expiring link to their email address, and never send the old password, because you do not have it. Require a new password to be set on the page behind the link.

Should I add multi-factor authentication?

It greatly reduces account takeover, and many services now support it. Check what your framework or identity provider offers.

Progress is saved in this browser.