Most 2FA Bugs Aren't Cryptography Bugs
The HMAC-based algorithm underneath TOTP and HOTP is simple, well-specified, and essentially impossible to get wrong if you follow RFC 6238 or RFC 4226 directly. Almost every real 2FA bug report traces back to something else entirely: which algorithm variant was chosen, how backup codes are stored, or a clock that's drifted by more than the verification window tolerates.
Step 1: Choose TOTP, Not HOTP, Unless You Have a Specific Reason Not To
Both algorithms compute an HMAC over a counter and truncate it into a short numeric code. The only real difference is where the counter comes from:
- TOTP (RFC 6238): counter = current Unix time ÷ a fixed period (usually 30 seconds). Both sides compute it independently from their own clock — no state to synchronize.
- HOTP (RFC 4226): counter = an explicit integer that increments every time a code is generated and accepted. Both sides must persist and agree on its current value.
TOTP: counter = floor(unix_time / 30) — no synchronization needed
HOTP: counter = stored_value, incremented on each use — must stay in sync
HOTP's counter-sync requirement is exactly the kind of state that drifts in production: a user's token advances (they pressed the button without submitting), a server-side counter update fails to commit, a retry double-increments. TOTP sidesteps all of it by using time, which both sides already have. Unless you're integrating with specific hardware tokens that only speak HOTP, default to TOTP.
Step 2: Get the otpauth:// URL Format Right
Every authenticator app's QR-code setup flow reads the same URL scheme:
otpauth://totp/Issuer:account@example.com?secret=JBSWY3DPEHPK3PXP&issuer=Issuer&algorithm=SHA1&digits=6&period=30
A few details that are easy to get wrong:
issuerappears twice — once in the label path (Issuer:account) and once as a query parameter. Most apps use the query parameter when present and fall back to the label; set both to the same value for compatibility across apps that only check one.- The label needs URL-encoding if it contains special characters — a raw
@or space in an unencoded label breaks parsing in some stricter clients. algorithm,digits, andperiodall have defaults (SHA1, 6, 30) that the overwhelming majority of authenticator apps assume even if the parameter is omitted — but don't omit them if you're using non-default values, since a client that doesn't read a parameter will silently fall back to the default and compute the wrong code.