TOTP Generator · 7 min read
How TOTP Works — The Math Behind Your 6-Digit 2FA Code
Time-based One-Time Passwords use HMAC-SHA1 and Unix timestamps to generate codes that change every 30 seconds. Learn the full algorithm behind your authenticator app.
Starting With HOTP: Counter-Based One-Time Passwords
TOTP builds on an older algorithm called HOTP (HMAC-Based One-Time Password), defined in RFC 4226. HOTP generates a one-time code from a shared secret and a counter. Each time the user authenticates, the counter increments. The server and client maintain synchronized counters, and the code is valid as long as the counters match within a small window.
The problem with HOTP: counter synchronization. If the user generates several codes without using them (by accidentally pressing the button), the client counter advances ahead of the server counter, causing authentication failures.
TOTP: Using Time as the Counter
TOTP (RFC 6238) replaces the sequential counter with time. The counter input is calculated as:
T = floor(Unix timestamp / 30)
The Unix timestamp is the number of seconds since January 1, 1970 UTC. Dividing by 30 and taking the floor gives a value that changes every 30 seconds and is identical for any device that knows the current time — no synchronization required. Both your authenticator app and the server independently compute the same value of T and therefore generate the same code.
The Shared Secret
TOTP requires a shared secret known to both the authenticator app and the server. This secret is typically 20 bytes (160 bits) of random data, encoded as a base32 string for readability and QR code compatibility. When you scan a QR code to set up an authenticator app, you are scanning an otpauth:// URL that contains this base32-encoded secret.
The secret must be stored securely on both ends. On the server, it is the equivalent of a password hash — if an attacker obtains it, they can generate valid codes indefinitely. On the app, it is stored in the device's secure enclave or encrypted storage.
The TOTP Algorithm Step by Step
Given the shared secret K and the current time, generating a 6-digit TOTP code involves five steps:
- Calculate T:
T = floor(current Unix time / 30). This gives the current 30-second time window as an integer. - Convert T to 8 bytes: Represent T as an 8-byte big-endian integer (most significant byte first).
- Compute HMAC-SHA1:
HS = HMAC-SHA1(K, T_bytes). The result is a 20-byte (160-bit) HMAC value. - Dynamic truncation: Take the last byte of the HMAC and look at its lowest 4 bits — this gives an offset value (0–15). Extract 4 bytes starting at that offset from the HMAC. Mask the most significant bit to produce a 31-bit number.
- Compute the OTP: Take
truncated_value mod 106to get a number between 0 and 999999. Left-pad with zeros to always produce 6 digits.
The dynamic truncation step (step 4) was designed to extract a 4-byte integer from a position within the HMAC that varies with the HMAC output itself — adding one more layer of unpredictability.
Why 30 Seconds?
The 30-second window balances security and usability. A shorter window would require more precise clock synchronization between devices and give users less time to enter the code. A longer window would give attackers more time to use an intercepted code.
Most implementations also accept codes from the immediately adjacent windows (the previous 30 seconds and the next 30 seconds) to tolerate minor clock drift. NIST's SP 800-63B recommends allowing at most one window of clock drift in each direction.
TOTP vs SMS 2FA
SMS-based 2FA sends the one-time code via text message. It is vulnerable to SIM swapping — an attack where the attacker convinces a mobile carrier to transfer a victim's phone number to an attacker-controlled SIM, intercepting all subsequent SMS messages. High-profile SIM swap attacks have been used to steal cryptocurrency, bypass account security, and commit identity theft.
TOTP avoids this attack entirely: the secret never leaves the authenticator app, and codes are generated locally without any communication that can be intercepted. NIST's 2017 guidelines deprecated SMS-based OTP as a standalone authentication factor specifically because of SIM swapping risk.
TOTP vs Hardware Tokens (YubiKey)
Hardware tokens like YubiKey implement TOTP and other standards (FIDO2, FIDO U2F, OTP) in dedicated hardware. The secret is stored on a tamper-resistant chip that cannot be extracted. Even if your computer is compromised by malware, a hardware token's secret remains safe.
App-based TOTP (Google Authenticator, Authy, 1Password) is highly resistant but not immune: if the device is compromised by malware with file system access, the stored secrets could be extracted. For the highest security requirements — protecting infrastructure, developer accounts, or high-value targets — hardware tokens provide a meaningful additional guarantee.
References
- M'Raihi, D., Machani, S., Pei, M., & Rydell, J. (2011). RFC 6238: TOTP: Time-Based One-Time Password Algorithm. Internet Engineering Task Force.
- M'Raihi, D., Bellare, M., Hoornaert, F., Naccache, D., & Ranen, O. (2005). RFC 4226: HOTP: An HMAC-Based One-Time Password Algorithm. Internet Engineering Task Force.
- NIST. (2017). Special Publication 800-63B: Digital Identity Guidelines — Authenticator and Verifier Requirements. National Institute of Standards and Technology.
- Krebs, B. (2022). SIM Swapping — How Criminals Hijack Phone Numbers and Why 2FA via SMS Is Risky. Krebs on Security.