Sub topic 6
Under the hood: how a TOTP code is computed and verified
This chapter assumes you have already enrolled an authenticator app on an account. You should also be able to read short Python and know what a hash is. Here you will see where the six digits on your phone come from and how an exchange checks them. You will also see why the scheme is strong against some attacks and helpless against others.
The ingredients
A time-based one-time password (TOTP) is defined in RFC 6238. It builds on HOTP, the counter-based version in RFC 4226. Both sides need only three things:
- A shared secret, a random byte string stored by the exchange and by your app.
- A clock, which is the current Unix time.
- Parameters: the hash algorithm, number of digits, and step length.
No network traffic is needed between the app and the exchange when a code is generated. Your phone can be offline. The code is a pure function of the secret and the time.
What the QR code carries
When you enroll, the exchange shows a QR code. It encodes an otpauth:// URI:
otpauth://totp/Example%20Exchange:alice%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Example%20Exchange&algorithm=SHA1&digits=6&period=30The secret is the shared key, written in base32. The issuer and the account name are labels for the app's list. The algorithm, digits and period fields set the parameters. Most apps use SHA1, 6 digits and 30 seconds, and some apps ignore the other values.
The computation, step by step
- Decode the secret. Base32 uses the letters A–Z and the digits 2–7. The code pads it with
=to a multiple of 8 characters, then decodes it to raw bytes. - Compute the counter. Divide the Unix time by the step length and drop the fraction:
counter = floor(time / 30). Every 30-second window gets one integer. - Pack the counter as an 8-byte big-endian integer.
- Compute HMAC-SHA1 of those 8 bytes, keyed with the secret. The result is 20 bytes.
- Dynamic truncation. Take the low 4 bits of the last byte as an offset from 0 to 15. Read the 4 bytes starting at that offset. Clear the top bit so the number is not negative.
- Reduce. Take the number modulo 10^digits and pad with leading zeros.
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 (ASCII "12345678901234567890") at Unix time 59
print(totp("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", at=59)) # 287082A worked example
The RFC 6238 test vectors use the ASCII secret 12345678901234567890, which is the base32 string in the code above. At Unix time 59:
- The counter is
59 // 30 = 1. - The HMAC-SHA1 of the counter is
75a48a19d4cbe100644e8ac1397eea747a2d33ab. - The last byte is
0xab. Its low 4 bits are0xb, so the offset is 11. - The four bytes from offset 11 are
c1 39 7e ea. Clearing the top bit turnsc1into41, which gives0x41397eea, or 1,094,287,082. - Modulo 10^8 that is
94287082, the value the RFC lists. Modulo 10^6 it is287082, the six-digit code.
If your function reproduces the RFC vector, your implementation is correct. Check this before you trust any home-made verifier.
The 30-second boundary
The counter changes at fixed multiples of the step, not 30 seconds after you opened the app. A code shown with 2 seconds left will be stale by the time you type it. Servers handle this, and clock drift, with a window.
Verifying on the server
The server runs the same function for the counters around "now" and compares each result with what you typed.
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)
)A window of 1 accepts the previous, current and next step, so a code is valid for up to about 90 seconds. hmac.compare_digest compares in constant time, so response timing does not leak how many digits matched.
A real server needs more than this function:
- Replay protection. A code is valid for the whole window, so someone who sees it can reuse it within that time. RFC 6238 says a verifier must not accept a second attempt with the same code. The server stores the last accepted counter per user and rejects any counter that is not greater.
- Rate limiting. There are only 10^6 possible six-digit codes, and about three are valid at any moment. Without lockouts, an attacker can try codes at speed. Limit failed attempts per account and per IP address.
- A recoverable secret. The server cannot store a hash of the secret, because it must compute HMACs with the raw key. It has to keep the key encrypted at rest. A breach of that store exposes every user's codes, which is a structural weakness compared with passkeys, where the server holds only public keys.
The next sketch adds replay protection. It reuses totp from above.
last_counter = {} # user -> last accepted counter (use a database in practice)
def verify_once(user, secret_b32, submitted, window=1, step=30):
now = time.time()
for drift in range(-window, window + 1):
counter = int(now // step) + drift
expected = totp(secret_b32, step=step, at=counter * step)
if hmac.compare_digest(expected, submitted):
if counter <= last_counter.get(user, -1):
return False # code already used, or older than one used
last_counter[user] = counter
return True
return FalseGotchas and failure modes
| Problem | Cause | Effect |
|---|---|---|
| Codes are always rejected | Phone clock is off by more than the window | Fix the time with automatic network time. |
| Wrong code from a manual key | Typo in base32 or lowercase or missing padding | The decoded key differs, so every code differs. |
| Lost phone | The secret lives only in the app | You need backup codes or an exported secret (see the recovery chapter). |
| Stolen secret | Screenshot, cloud backup, shoulder-surfing | The attacker produces valid codes silently. |
| Real-time phishing | The user types a valid code into a fake site | The attacker relays it to the real site within the window. |
The last row is the main limit. TOTP proves that you hold the secret, but it never checks which website you are typing the code into. A phishing proxy can forward your password and your code within seconds. A passkey signs a challenge bound to the site's origin, so a lookalike domain cannot use it. That mechanism is the subject of later chapters.
TOTP still beats SMS. Nothing travels over the phone network, so a SIM swap does not expose it. The code can be generated offline, and the secret never leaves the device after enrollment unless you export it.
Exercise
At Unix time 89, what counter value does a 30-second TOTP use, and would a server with window=1 that checks at time 89 accept a code the app generated at time 59?
Show answer
The counter at time 89 is floor(89 / 30) = 2. The code generated at time 59 used counter 1. A window of 1 checks counters 1, 2 and 3, so the server accepts it, provided it has not accepted that code before.
Exercise
Why can a server not store only a hash of the TOTP secret, the way it stores a password hash?
Show answer
The server must compute HMAC-SHA1 with the raw secret each time it verifies a code. A hash of the secret cannot be used as the HMAC key to reproduce the code. So the server must keep the secret in recoverable form, which is why it should be encrypted at rest and why a breach of that store is serious.