TOTP, HOTP, and Why Your 2FA Actually Works
You open Google Authenticator, see a 6-digit code, type it into the login form, and the server says yes. There is no network call from your phone to the server. The server does not have a list of "codes you have given out". You both arrive at the same number through math. This post is about that math.
HOTP first, then TOTP
RFC 4226 (2005) defines HOTP, HMAC-based One-Time Password. The recipe:
- The user and the server share a secret K (random bytes, typically 160 bits).
- The user and the server share a counter C, starting at 0 and incrementing on each use.
- Code = truncate(HMAC-SHA1(K, C)) modulo 10^6 for a 6-digit code.
The counter is the clever part. Every code is a one-shot: once used, the counter advances, and that code is invalid forever. The server stores the last counter it accepted; codes that arrive with a counter at or below the last-accepted are rejected.
HOTP is rare in the wild because synchronizing counters between client and server is annoying. If the user presses "generate" three times before logging in, the counter drifts. RFC 4226 specifies a look-ahead window (the server accepts codes for the next N counter values), but the extra state makes it less convenient than TOTP.
TOTP: the counter is just time
RFC 6238 (2011) replaces the counter with a time-based value:
T = floor(unix_time / 30) code = truncate(HMAC-SHA1(K, T)) % 10^6
That is the whole change. The counter comes from wall-clock time divided by the period, and 30 seconds is the default the RFC recommends. The two sides do not need to synchronize a counter. They just need clocks that are close.
The advantages:
- No state synchronization. Both sides compute the same T independently.
- Codes are inherently time-limited. After 30 seconds the code is invalid.
- Users can press "generate" as many times as they want; the same T returns the same code.
The trade-off: without extra work, a code stays valid for its whole window. RFC 6238 requires the verifier to refuse a second use of a code that has already been accepted, which takes server-side state. Pitfall 4 below covers it.
The "truncate" step
HMAC-SHA1 produces 160 bits (20 bytes). You need a 6-digit number. The truncation is more careful than just "take the last 6 digits":
function truncate(hmac):
offset = hmac[len(hmac)-1] AND 0x0F // last 4 bits of last byte
binary = (hmac[offset] AND 0x7F) << 24
| (hmac[offset+1] AND 0xFF) << 16
| (hmac[offset+2] AND 0xFF) << 8
| (hmac[offset+3] AND 0xFF)
return binary mod 10^6 // for 6-digit code
RFC 4226 calls this dynamic truncation: the last four bits pick where to read a 4-byte window from the HMAC output, giving a 31-bit number that is then reduced to the digit count. The high bit is masked to avoid confusion between signed and unsigned arithmetic in different languages.
Check your implementation against the RFC
RFC 6238's test vectors use the ASCII secret 12345678901234567890. At Unix time 59, T is 1 and the 8-digit SHA-1 code is 94287082, so the 6-digit code is 287082. RFC 4226 gives 755224 for HOTP with the same secret at counter 0. If your code produces these, the byte order, truncation, and HMAC are right.
Why 6 digits and not 8?
RFC 4226 requires at least 6 digits, and RFC 6238 allows up to 8. Six became the norm, and authenticator apps do not all handle other lengths the same way: some ignore the setting and show 6 digits, which fails verification. Stick with 6 unless you have tested the apps your users have.
Clock drift
A 30-second window makes clock drift a real problem. If the phone is 35 seconds slow, the code it shows belongs to an earlier window. Servers usually handle this by also checking neighboring windows:
function verify(code, secret, period=30, drift_windows=1):
now = floor(now() / period)
for off in range(-drift_windows, drift_windows + 1):
if constant_time_equal(hotp(secret, now + off), code):
return True
return False
One window in each direction accepts three codes at any moment, for roughly 90 seconds of validity in total. RFC 6238 recommends allowing no more than one step of network delay. Zero tolerance is stricter and leads to more failed logins from slow clocks. Compare codes in constant time, as above, so response timing does not reveal matching digits.
SHA-1 in 2026?
SHA-1 is broken for collision resistance. TOTP uses it inside HMAC, which does not depend on collision resistance, and no practical attack on HMAC-SHA1 is known. The RFC allows SHA-256 and SHA-512, but authenticator app support is inconsistent, so SHA-1 remains the compatible choice.
Common implementation pitfalls
1. Using time in milliseconds instead of seconds
The math expects floor(unix_time / 30) where unix_time is seconds since epoch. If you accidentally pass milliseconds, your T value is 1000x too high, and your codes look random instead of matching. The token is technically valid in some far-future window.
2. Wrong byte order
The counter T must be encoded as 8 bytes big-endian for the HMAC input. JavaScript's DataView.setBigUint64 defaults to big-endian, which is correct. Manual byte assembly sometimes gets this wrong, producing codes that match no authenticator app.
3. Forgetting Base32 decoding
Secrets are usually shared as Base32 text, often in a QR code. Your code must decode that text to bytes before the HMAC. Using the Base32 string's own characters as the key produces codes that match no authenticator app.
4. Replay protection
Store the most recently accepted time step for each user and reject anything at or below it. Without this, an attacker who captures a code can reuse it within its window. Many TOTP libraries only compute and compare codes and leave this storage to you, so check yours.
5. Treating the secret like a password hash
The server needs the shared secret itself to compute codes, so it cannot store a one-way hash of it. Encrypt secrets at rest with a key kept outside the database, and limit attempts on the verification endpoint: six digits is only a million possibilities.
When NOT to use TOTP
For very high-stakes accounts: security keys and passkeys (FIDO2/WebAuthn) bind authentication to the specific domain, so they resist phishing. TOTP does not: a user who types a code into a lookalike site has handed it to the attacker, who can use it right away.
Compared with SMS: TOTP is the better option where you can use it, because SMS codes are exposed to SIM swapping and interception.
For frequent, repeated authorization: asking for a new code on every action is tedious. Use a session or signed token after the initial login, and step up with a second factor only for sensitive actions.