Sub topic 6
Under the Hood: How a TOTP Code Is Computed and Verified
This chapter assumes you understand passwords and two-factor authentication, and that you can read short Python programs. TOTP is a standard way to create a temporary code from a shared secret and the current time. TOTP means time-based one-time password.
The inputs to TOTP
During enrollment, the exchange creates a random secret. The authenticator app stores the same secret. Usually, the secret is encoded with Base32 so it can be placed in a QR code or typed manually.
Each code depends on:
- The shared secret.
- The current Unix time, measured in seconds since January 1, 1970.
- A time step, usually 30 seconds.
- A hash algorithm, commonly HMAC-SHA1.
- The number of digits, commonly six.
The QR code normally contains an otpauth URI:
otpauth://totp/Example%20Exchange:alice%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Example%20Exchange&algorithm=SHA1&digits=6&period=30The URI is sensitive. Anyone who obtains the secret can generate valid codes.
The calculation
TOTP first divides the current time by the time step. This produces a counter. Every 30 seconds, the counter increases by one.
The counter is packed as an eight-byte big-endian integer. HMAC then combines that counter with the shared secret. HMAC is a keyed hash: it produces a value that only someone with the secret can reproduce.
The result is a 20-byte HMAC-SHA1 value. TOTP uses dynamic truncation to select four bytes from that value. It clears the highest bit, converts the result to an integer, and takes the remainder modulo one million. Padding with zeros produces a six-digit code.
import base64
import hashlib
import hmac
import struct
def totp(secret_b32, at, step=30, digits=6):
padding = "=" * (-len(secret_b32) % 8)
key = base64.b32decode(secret_b32.upper() + padding)
counter = int(at // step)
message = struct.pack(">Q", counter)
digest = hmac.new(key, message, hashlib.sha1).digest()
offset = digest[-1] & 0x0F
number = struct.unpack(">I", digest[offset:offset + 4])[0]
number &= 0x7FFFFFFF
return str(number % (10 ** digits)).zfill(digits)
# RFC 6238 test vector: ASCII "12345678901234567890", at time 59.
print(totp("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", at=59))
# 287082Verification and common errors
The server repeats the calculation with its copy of the secret. Because phones and servers may differ slightly, a server often accepts the current time step plus one step before and after it. This is called a verification window.
A wider window improves tolerance but gives an attacker more chances to guess. The server should also reject a code that was already accepted for the same account and time step. TOTP is temporary, but it is not automatically single-use.
Servers should compare submitted codes in constant time. This reduces information leaked through timing differences. They should rate-limit failures and protect the secret at rest. A clock that is badly wrong can cause every valid code to fail.
| Problem | Result | Useful control |
|---|---|---|
| Phone clock is inaccurate | Valid codes fail | Automatic time synchronization |
| Window is too wide | More guesses are accepted | Keep the window small |
| Secret is exposed | An attacker generates codes | Protect enrollment and stored secrets |
| Code is reused | A captured code may work again | Track accepted time steps |
Exercise
Why does a TOTP code change even though the shared secret stays the same?
Show answer
The code uses a counter derived from the current time. When the time-step counter changes, HMAC receives a different input and produces a different code.