How a 2FA code is made
The six digits are not random and not fetched from anywhere. Your phone and the website share a secret, and both compute the same thing from the clock. Below, a demo secret runs through the real algorithm (RFC 6238, built on RFC 4226), live, in this tab.
Demo secret (public, from the RFC test vectors; never use it for an account): GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ
1. Time becomes a counter
Take the Unix time in seconds and divide by the period (30 s), rounding down. Every 30 seconds the counter goes up by one. That is why the code changes.
- Unix time
- Counter
2. The counter becomes 8 bytes
The counter is written as a 64-bit big-endian number. These are the bytes that get signed.
3. HMAC with the secret
The 8 bytes are signed with HMAC-SHA1, using the secret as the key. Only someone who knows the secret gets this result. It is 20 bytes long.
4. Dynamic truncation
The last hex digit of the HMAC (here …) says where to start. The 4 bytes from there, with the top bit cleared, make a 31-bit number.
5. Keep the last six digits
The number is divided by 1,000,000. The remainder, padded with zeros to six digits, is the code.
Questions
Why does the code change every 30 seconds?
Because the counter is the clock divided by 30 seconds. A new counter gives a completely different HMAC, so a completely different code.
How do the server and the phone agree without talking?
They share the secret once, when you scan the QR code. After that each side only needs the time, and both have it.
Why can a correct secret still give a rejected code?
The clock is off. If the phone differs from the server by more than about 30 seconds, the counters differ. Turn on automatic time. The main tool’s “Check a code” shows how far off you are.
Is it safe to compute a code in a web page?
The math is the same as in any app. What matters is where the secret goes. This page makes no request except one for the time, and you can check that in your browser’s Network tab.
Compute your own code Try any time or secret on the developer page