Security · 4 min read
How TOTP Two-Factor Codes Work
Authenticator apps such as Google Authenticator and 1Password show a six-digit code that changes every 30 seconds — and they do it completely offline. The trick is an open standard called TOTP (RFC 6238), and it is simpler than it looks.
Try it yourself with the related tool.
Generate TOTP codes →Advertisement
The shared secret
When you enable two-factor authentication, the site generates a random secret and shows it as a QR code. The QR code holds an otpauth://totp/... URL containing the secret in Base32, plus the issuer name, the number of digits, and the time step. Your app stores the secret; the server stores the same secret. Nothing else is ever exchanged.
From time to six digits
Both sides take the current Unix time and divide it by 30, giving a counter that ticks up every 30 seconds. They compute an HMAC-SHA1 of that counter using the secret, pick four bytes from the result, and reduce them to six digits. Because both have the same secret and roughly the same clock, they arrive at the same code independently.
Why codes sometimes fail
TOTP depends on the clock. If a phone's time drifts by a minute, its codes will not match. Servers usually accept the codes for one step either side to absorb small drift and typing delays. If codes fail persistently, turning on automatic time sync on the device almost always fixes it.
Keep the secret secret
Anyone with the secret can generate valid codes forever, so treat the QR code like a password: never screenshot it into shared folders, and save the recovery codes the site gives you. TOTP also does not stop real-time phishing — a fake login page can relay the code — which is why passkeys and hardware keys are stronger still.
