π’ How a TOTP code is calculated
The six digits in your authenticator app (or on your YubiKey, or from oathtool in the terminal) are not random. They are calculated from two things: a shared secret and the current time. Your phone and the server both do the same calculation, so they get the same code without ever talking to each other.
The recipe is open: HOTP (RFC 4226) and TOTP (RFC 6238).
1. The ingredients
- The secret $K$: random bytes that you get once, as the QR code or as a base32 text such as
JBSWY3DPEHPK3PXP. The QR code is just this text in anotpauth://link. - The time $T$: the number of seconds since 1 January 1970 (Unix time).
- The step $X$: usually 30 seconds, so a code is valid for 30 seconds.
- The number of digits $d$: usually 6.
2. From time to a counter
TOTP first turns the time into a counter that goes up by one every 30 seconds:
$$C = \left\lfloor \frac{T - T_0}{X} \right\rfloor$$with $T_0 = 0$. For example at $T = 1,700,000,000$:
$$C = \left\lfloor \frac{1\,700\,000\,000}{30} \right\rfloor = 56\,666\,666$$Everybody who calculates within the same 30 seconds gets the same $C$.
3. HMAC: mix the secret with the counter
The counter is written as 8 bytes (big-endian) and put through HMAC-SHA1 with the secret as key:
$$H = \operatorname{HMAC\text{-}SHA1}(K, C)$$$H$ is 20 bytes (160 bits). HMAC is a one-way function: from a code you can’t work back to the secret, and without the secret you can’t predict the next code.
4. Dynamic truncation: from 20 bytes to 6 digits
From the 20 bytes, 4 are chosen. Which 4 depends on the hash itself:
- Take the last byte, and keep its lowest 4 bits: that is the offset $o$ (0β15).
- Take the 4 bytes starting at position $o$: $H[o], \dots, H[o+3]$.
- Throw away the highest bit, so the number is always positive (31 bits).
- Keep the last $d$ digits:
Pad it with zeros on the left if it is shorter than 6 digits.
All together:
$$\operatorname{TOTP}(K, T) = \operatorname{Truncate}\!\Big(\operatorname{HMAC\text{-}SHA1}\big(K, \lfloor T/30 \rfloor\big)\Big) \bmod 10^{6}$$HOTP is the same formula with a counter that goes up at every login instead of with the time.
5. Check it yourself in Python
import base64, hmac, hashlib, struct, time
def totp(secret_b32, t=None, digits=6, period=30):
key = base64.b32decode(secret_b32.upper() + "=" * (-len(secret_b32) % 8))
counter = int(time.time() if t is None else t) // period # step 2
h = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest() # step 3
o = h[-1] & 0x0F # step 4.1
p = struct.unpack(">I", h[o:o + 4])[0] & 0x7FFFFFFF # step 4.2-4.3
return str(p % 10 ** digits).zfill(digits) # step 4.4
print(totp("JBSWY3DPEHPK3PXP")) # the code right now
print(totp("JBSWY3DPEHPK3PXP", t=1700000000)) # 324550
Compare it with oathtool:
oathtool -b --totp JBSWY3DPEHPK3PXP
oathtool -b --totp -N "@1700000000" JBSWY3DPEHPK3PXP # 324550
The RFC has official test values. With the ASCII secret 12345678901234567890, 8 digits and $T = 59$, the code must be 94287082:
key = base64.b32encode(b"12345678901234567890").decode()
print(totp(key, t=59, digits=8)) # 94287082
6. Why it is safe (and where it isn’t)
- Guessing a code: there are $10^6$ possible codes, so one guess has a one-in-a-million chance. Servers allow only a few attempts, so guessing doesn’t work.
- A stolen code is worthless after 30 seconds (most servers also accept the code before and after, for clocks that are a bit off).
- The weak spot is the secret. Whoever has the secret can make every future code. That’s why the secret belongs in a safe place: encrypted with GPG or, better, on a YubiKey, where it can’t be copied.
- Phishing: a fake website can ask for your code and use it straight away. FIDO2 / passkeys protect against that; TOTP doesn’t.
SHA-1 is broken for collisions, but that doesn’t matter here: HMAC-SHA1 is still considered safe, and the RFC also allows HMAC-SHA256 and HMAC-SHA512.
Related: Key Derivation Function, about how passwords are turned into keys.