← All lessons
How authenticator codes work
From a shared secret to six digits
Authenticator
shop.test
totp.js
// once, when you turn on 2FAconst secret = crypto.getRandomValues(new Uint8Array(20));showQr(`otpauth://totp/shop:ana?secret=${base32(secret)}`); function totp(secret, now = Date.now() / 1000) { const T = Math.floor(now / 30); const msg = uint64BigEndian(T); const mac = hmacSha1(secret, msg); // 20 bytes const offset = mac[19] & 0x0f; const bin = ((mac[offset] & 0x7f) << 24) | (mac[offset + 1] << 16) | (mac[offset + 2] << 8) | mac[offset + 3]; return String(bin % 1e6).padStart(6, "0");}server.js
// one step either side, and never the same step twicefunction check(user, code) { const T = Math.floor(Date.now() / 1000 / 30); for (const step of [T - 1, T, T + 1]) { if (step <= user.lastStep) continue; // already used if (totp(user.secret, step * 30) === code) { user.lastStep = step; return true; } } return false;}Your own authenticator then knock its clock off
The app shows
··· ···
The server accepts
RFC 6238 test vector, 59 s:
Don't paste a real account's secret here. It stays in this tab, but a secret is the whole key
server.js
// one step either side, and never the same step twicefunction check(user, code) { const T = Math.floor(Date.now() / 1000 / 30); for (const step of [T - 1, T, T + 1]) { if (step <= user.lastStep) continue; // already used if (totp(user.secret, step * 30) === code) { user.lastStep = step; return true; } } return false;}Topics
Next: How Content Security Policy works
Open lesson