Sub topic 2
Under the hood: how a TOTP code is computed and verified
This chapter assumes you have used an exchange account with two-factor authentication, can read short Python programs, and know that a hash function turns input into a fixed-length digest. The passkey sections assume basic familiarity with public-key cryptography.
How a TOTP code is computed
A time-based one-time password (TOTP) is a six-digit code that changes every 30 seconds. Your authenticator app and the exchange share a secret key, and both compute the same code from that key and the current time:
- Divide the Unix time by 30 to get a counter. Both sides get the same counter.
- Compute an HMAC-SHA1 of the counter, using the shared secret as the key.
- Pick four bytes from the result at an offset set by the last byte (dynamic truncation).
- Reduce that number modulo 10^6 to get six digits.
import base64
import hashlib
import hmac
import struct
import time
def totp(secret_b32, step=30, digits=6, at=None):
key = base64.b32decode(secret_b32.upper() + "=" * (-len(secret_b32) % 8))
now = time.time() if at is None else at
counter = int(now // step)
mac = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
offset = mac[-1] & 0x0F
value = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
return str(value % 10 ** digits).zfill(digits)
if __name__ == "__main__":
# RFC 6238 test secret at Unix time 59
print(totp("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", at=59)) # 287082How the server verifies a code
The server runs the same computation. It accepts codes from one step before and one step after the current time, which allows for clock drift.
def verify_totp(secret_b32, submitted, window=1, step=30):
now = time.time()
return any(
hmac.compare_digest(totp(secret_b32, step=step, at=now + drift * step), submitted)
for drift in range(-window, window + 1)
)Key pairs, signatures and challenges
A passkey uses public-key signatures instead of a shared secret. The device creates a key pair: a private key that never leaves the device, and a public key that it sends to the exchange. To sign in, the exchange sends a random challenge. The device signs the challenge with the private key, and the exchange checks the signature with the stored public key. Because the server stores only the public key, a database leak does not expose anything an attacker can use to sign in.
Passkeys and WebAuthn: registering and signing in
WebAuthn is the browser interface for passkeys and FIDO2 security keys. The exchange's page calls two browser functions: one to register a key and one to sign in.
// Registration: the server supplies a random challenge and a user id.
const credential = await navigator.credentials.create({
publicKey: {
challenge: challengeBytes,
rp: { id: "exchange.example", name: "Example Exchange" },
user: { id: userIdBytes, name: "[email protected]", displayName: "Alice" },
pubKeyCredParams: [{ type: "public-key", alg: -7 }],
authenticatorSelection: { residentKey: "preferred", userVerification: "required" },
attestation: "none",
timeout: 60000
}
});
// Sign-in: the server supplies a fresh challenge for each attempt.
const assertion = await navigator.credentials.get({
publicKey: {
challenge: newChallengeBytes,
rpId: "exchange.example",
userVerification: "required"
}
});The server must check that the signature is valid, that the challenge is one it issued and has not used, and that the origin in the signed data matches its own site.
Why passkeys resist phishing: origin binding
The browser stores each passkey under the relying party ID, which is the exchange's domain. It signs the origin of the page that asked for the signature. A fake site at exchange-login.example cannot get a signature for exchange.example, so the passkey is never offered there.
| Attack | Authenticator app code | Passkey |
|---|---|---|
| Typed into a fake login page | Works until the 30-second window closes | Browser refuses to sign for the fake domain |
| Database leak | Shared secret may be exposed | Only public keys are stored |
Synced passkeys, device-bound passkeys and security keys
- Synced passkeys live in a platform password manager and copy across your devices. They are convenient, and their security depends on that account's protection.
- Device-bound passkeys stay on one device. They are harder to lose by accident, and harder to recover.
- Hardware security keys are USB or NFC devices that hold the private key. They are the strongest option, and a spare key is essential.
Setting up an authenticator app and a passkey on your exchange
- Open the exchange's security settings and choose to add an authenticator app.
- Scan the QR code with your app, then enter the six-digit code to confirm.
- Save the recovery codes the exchange shows you in an offline location.
- Open security settings again and add a passkey or security key.
- Sign out and sign in again, using the passkey to confirm it works.
- Register a second passkey or key on another device.
Exercise
The server accepts codes from one step before to one step after the current time. Why does a code captured at 12:00:05 still work at 12:00:20, and what extra check stops a replay?
Show answer
The window tolerates clock drift, so the code for the 12:00:00 step still verifies until the window moves past it. The server must also store the last accepted counter for each user and reject any code with that counter or an earlier one.