The authenticator app on Siti's phone has no connection to the School Portal server. No SMS, no notification, the phone can even be in airplane mode. Yet the 6-digit code on its screen is accepted by the server. How?
That's TOTP (Time-based One-Time Password, the RFC 6238 standard) at work: a 6-digit code that changes every 30 seconds, used as the second factor after the password. The server and the authenticator app on a phone (Google Authenticator, Authy, 1Password) each compute the same code on their own, without sending each other anything. Picture two people holding exactly the same codebook, one page for every half minute. The clock says which page is current, so both open the same page and read the same number. The codebook is the secret, and the page number comes from the clock.
Turning on 2FA: the secret is shared once
Siti turns on 2FA on her School Portal profile page. What happens:
- The server makes a secret: 20 random bytes from
crypto.getRandomValues(160 bits), written in base32, the letters A to Z and the digits 2 to 7, so a person can type it. - The server shows that secret as an
otpauth://URI, usually drawn as a QR code. Siti scans it with her authenticator app, and the app stores the secret. - The server asks for one code from the app. Only if it matches is 2FA turned on. That proves Siti really saved the secret.
This lesson and its Lab use RFC 6238's test secret, the text 12345678901234567890, so you can check the results yourself. Its URI:
otpauth://totp/School%20Portal:siti%40school.test?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=School%20Portal&algorithm=SHA1&digits=6&period=30
totpis the type,School Portal:[email protected]the label the app shows (its special characters encoded as%20and%40).secretis in base32,issueris the app's name, andalgorithm,digits,periodare the standard values: SHA1, 6 digits, 30 seconds.
The secret is shared once only, at setup. The server stores it encrypted, because whoever holds the secret can make every one of Siti's codes.
From a secret and a clock to six digits
On the phone and on the server, the recipe is the same:
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
function base32Decode(text) {
let bits = 0, value = 0;
const bytes = [];
for (const ch of text.replace(/=+$/, "").toUpperCase()) {
const idx = ALPHABET.indexOf(ch);
if (idx < 0) throw new Error("not a base32 letter: " + ch);
value = (value << 5) | idx; // each letter carries 5 bits
bits += 5;
if (bits >= 8) {
bytes.push((value >>> (bits - 8)) & 0xff); // emit one whole byte
bits -= 8;
}
}
return new Uint8Array(bytes);
}
async function totp(secretBase32, unixSeconds, digits = 6) {
const counter = Math.floor(unixSeconds / 30); // which 30-second step
const msg = new Uint8Array(8); // the counter as 8 bytes, big-endian
for (let i = 7, c = counter; i >= 0; i--, c = Math.floor(c / 256)) msg[i] = c & 0xff;
const key = await crypto.subtle.importKey("raw", base32Decode(secretBase32), { name: "HMAC", hash: "SHA-1" }, false, ["sign"]);
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, msg)); // 20 bytes
const offset = mac[19] & 0x0f; // dynamic truncation
const bin = ((mac[offset] & 0x7f) << 24) | (mac[offset + 1] << 16) | (mac[offset + 2] << 8) | mac[offset + 3];
return String(bin % 10 ** digits).padStart(digits, "0");
}
Math.floor(unixSeconds / 30)is the counter: how many 30-second steps have passed since 1 January 1970. For 30 seconds the counter stays the same, so the code does too. The unit is seconds; JavaScript'sDate.now()is milliseconds, so divide by 1000 first.- The counter is written as 8 bytes, biggest byte first (big-endian), because that is the message HMAC signs.
crypto.subtle.sign("HMAC", ...)withSHA-1gives the HMAC-SHA1: 20 bytes only a holder of the secret can make.- Dynamic truncation: the last 4 bits of the 20th byte pick the
offset, and the 4 bytes from there are taken.& 0x7fdrops the top bit so the number is always positive. % 10 ** digitskeeps the last 6 digits, andpadStartadds leading zeros. The code042891must stay 6 characters, so the code is a string, not a number.
Check it against RFC 6238's test vector
RFC 6238 has a test table (Appendix B): secret 12345678901234567890, time T = 59, 8 digits, must give 94287082. This is the trace of the totp function above, exactly what the Lab computes:
| Step | Value |
|---|---|
| counter | Math.floor(59 / 30) = 1 |
| 8-byte counter | 00 00 00 00 00 00 00 01 |
| HMAC-SHA1 | 75a48a19d4cbe100644e8ac1397eea747a2d33ab |
| offset | last byte ab, 0xab & 0x0f = 11 |
| 4 bytes from byte 11 | c1 39 7e ea |
| top bit dropped | 0x41397eea = 1,094,287,082 |
% 10 ** 8 |
94287082, the same as the RFC |
% 10 ** 6 |
287082 |
If your implementation gives 94287082 for this input, it is right. With the same secret, Friday 9 October 2026 at 07:00:00 school time, UTC+7 (Unix 1791504000) is counter 59716800 and code 911338.
Verifying: a ±1 window and single-use codes
The server doesn't accept only the code computed for its own clock. A phone's clock is rarely exactly the server's; the difference is called clock drift. So the server tries three counters: one step back, now, and one step ahead.
async function verifyTotp(user, code, unixSeconds) {
const now = Math.floor(unixSeconds / 30);
for (const step of [-1, 0, 1]) { // room for a clock that is a little off
const counter = now + step;
if ((await totp(user.secret, counter * 30)) !== code) continue;
if (counter <= user.lastUsedCounter) return "already used"; // single-use codes
user.lastUsedCounter = counter; // stored in the database
return "accepted";
}
return "wrong";
}
School Portal's server clock says 07:00:10, but Siti's phone is 20 seconds behind, still at 06:59:50. Before you read on, guess: does verifyTotp accept the code on Siti's phone, or reject it?
The server at 07:00:10 is at counter 59716800 (code 911338). Siti's phone at 06:59:50 is still at counter 59716799 and shows 839888. That matches step -1, so the code is accepted. If the phone were more than one step behind, the code would be rejected.
Why only ±1? Every extra step means more codes valid at once, so guessing one gets easier. One step each way is what RFC 6238 recommends.
The lastUsedCounter line stops a replay: the same code sent again, say from a double-pressed button or someone glancing at the phone. Within that 90-second window the code still matches, so without this record it could be used again. The server stores the last accepted counter and rejects that counter or any older one.
The login flow with 2FA
POST /login {email, password} password matches, 2FA is on
-> 200 {"two_factor": true} not logged in yet, the session only notes "waiting for a code"
POST /two-factor-challenge {code} verifyTotp: "accepted"
-> 302 Location: /dashboard logged in only now, the session ID regenerated
Also limit code attempts, say 5 a minute, because 6 digits have only a million possibilities. How is covered in Rate Limiting for Authentication. Why a second factor matters is covered in Multi-factor Authentication (MFA).
The exercise: HMAC-SHA1 without await
crypto.subtle.sign is always async, while the exercise below reads console.log straight away. So the starter code already brings hmacSha1(key, message): SHA-1 and HMAC written in plain JavaScript. It takes two byte arrays and returns the very same 20 bytes crypto.subtle.sign gives. You write the rest, the same steps as the totp function above:
function generateTotp(secret, timestamp) {
const counter = Math.floor(timestamp / 30);
const message = [];
for (let i = 7; i >= 0; i--) message.push(Math.floor(counter / 2 ** (8 * i)) & 0xff); // 8 bytes, big-endian
const mac = hmacSha1(secret, message); // 20 bytes
// ...then dynamic truncation and % 1000000, as in totp()
}
The exercise's secret is already bytes (the RFC's test secret, the text 12345678901234567890), so there's no base32Decode. The result is checked against RFC 6238's test vectors in 6 digits: T = 59 gives 287082, and T = 1234567890 gives 005924. verifyTotp(secret, code, timestamp) tries timestamp - 30, timestamp and timestamp + 30, and returns true when one of them equals code.
💡 Recovery codes and Laravel Fortify
Phones get lost. When 2FA is turned on, hand out 8 to 10 single-use recovery codes, store their hashes, and cross off the used ones. In Laravel, the official Fortify package provides all of this: the two_factor_secret (encrypted), two_factor_recovery_codes and two_factor_confirmed_at columns on users, the POST /two-factor-challenge route, and a check that rejects the same code used twice. One difference: Fortify makes 8 recovery codes and stores them encrypted with APP_KEY, not hashed, so they can be read again: the GET /user/two-factor-recovery-codes route shows them again.
⚠️ Codes that always fail, or pass too easily
- Milliseconds used as seconds.
Math.floor(Date.now() / 30)gives a completely wrong counter. Divide by 1000 first. - The code kept as a number.
42891is only 5 digits. The code042891must be a string; usepadStart(6, "0"). - A window that is too wide. Accepting ±10 steps rarely fails, but means 21 valid codes at once. ±1 is enough.
- No check for used codes. The same code can be used again while it is still in the window. Store the last accepted counter.
- The secret sent by email or stored as is. Show it once on the setup page, store it encrypted.
TL;DR: TOTP (RFC 6238) = HMAC-SHA1(secret, counter), with counter = Math.floor(unixSeconds / 30) as 8 big-endian bytes, then dynamic truncation (offset from the last 4 bits, 4 bytes, top bit dropped) and % 10 ** 6, with leading zeros. The secret is shared once through an otpauth:// URI (a QR code), in base32. The server tries counters -1, 0 and +1 for clock drift, and stores the last accepted counter so the same code can't be used twice. Check your implementation: secret 12345678901234567890, T = 59, 8 digits, must give 94287082.
⚡ The same secret, the same clock
Meaning: The server and the authenticator app each compute the same code on their own, without sending each other anything. The HMAC-SHA1 input is the same secret, plus the current time divided by 30 seconds. Like two people holding the same codebook: the clock says which page to open.
⚡ The secret is shared once
Meaning: When 2FA is turned on, the server makes a secret of 20 random bytes, written in base32 and shown as an otpauth:// URI (usually a QR code). The server stores it encrypted, because whoever holds the secret can make every one of Siti's codes.
⚡ A ±1 window and single-use codes
Write:
async function verifyTotp(user, code, unixSeconds) {
const now = Math.floor(unixSeconds / 30);
for (const step of [-1, 0, 1]) { // room for a clock that is a little off
const counter = now + step;
if ((await totp(user.secret, counter * 30)) !== code) continue;
if (counter <= user.lastUsedCounter) return "already used"; // single-use codes
user.lastUsedCounter = counter; // stored in the database
return "accepted";
}
return "wrong";
}
Guess first: the server clock says 07:00:10, but Siti's phone is 20 seconds behind, still at 06:59:50. Is the code on Siti's phone accepted?
Accepted. Siti's phone is still on the previous counter, and that matches step -1. If the phone were more than one step behind, the code would be rejected.
Meaning: lastUsedCounter stops a replay: the same code sent again while it is still inside the window is rejected straight away.