How TOTP authenticator codes work: the math behind the 6 digits
The six digits in your authenticator app are not random and they are not sent anywhere. They are computed on your phone from two ingredients that your phone and the server already share. Understanding the mechanism makes 2FA far less mysterious, and explains its few sharp edges.
The shared secret
When you enable two-factor authentication, the service generates a random secret key and shows it to you, usually as a QR code. Your authenticator app stores it. Now both sides hold the same secret, and crucially, it never travels again. That QR code is just a URL like otpauth://totp/Service:you@example.com?secret=BASE32SECRET&issuer=Service. The secret is the only sensitive part.
Time as the moving piece
TOTP stands for Time-based One-Time Password. The algorithm takes the current time, divides it into 30-second windows (the count of 30-second steps since the Unix epoch), and feeds that number plus the shared secret into an HMAC-SHA1 hash. The result is truncated down to six digits. Because both your phone and the server know the secret and roughly agree on the time, they compute the same code independently. Nothing is transmitted to verify it; the server just runs the same math and compares. You can see this in action with the OTP Generator, which produces TOTP codes from a secret in your browser.
This is why the code changes every 30 seconds: the time window advances. It is also why a stale code fails, and why an app on a phone with a badly wrong clock cannot log in. To stay forgiving, servers usually accept the previous and next window as well, giving you a minute or so of grace.
HMAC is doing the real work
The security rests on HMAC, the same keyed-hash construction used to sign API requests and webhooks. Without the secret, you cannot produce a valid code, and the six-digit output leaks nothing useful about the secret. If you want the deeper picture of how HMAC differs from a plain hash, see SHA-256 vs HMAC vs bcrypt, and generate signatures directly with the HMAC Generator.
Practical notes
- Back up the secret, not just the codes. If you lose the device and never saved the secret or recovery codes, you are locked out. The codes themselves are disposable; the secret is everything.
- TOTP is phishing-resistant only up to a point. A convincing fake login page can still relay a code in real time. Hardware keys and passkeys close that gap, but TOTP is a large step up from a password alone.
- The QR code is a secret. Anyone who photographs it can clone your second factor. Treat it like a password.
For a browser-based way to generate and test TOTP codes while you build or debug a login flow, keep the OTP Generator handy, and lean on the Timestamp Converter when you are reasoning about the 30-second windows.