How 2FA (TOTP) codes actually work – and why your code is "wrong"
Every time you type a 6-digit code from Google Authenticator, you're using TOTP – Time-based One-Time Passwords (RFC 6238). It's a surprisingly small algorithm, and once you see it, a lot of "my 2FA code doesn't work" pr
Every time you type a 6-digit code from Google Authenticator, you're using TOTP – Time-based One-Time Passwords (RFC 6238). It's a surprisingly small algorithm, and once you see it, a lot of "my 2FA code doesn't work" problems make sense.
The shared secret
When you enable 2FA, the service shows a QR code. Inside is a URI like:
otpauth://totp/GitHub:me?secret=JBSWY3DPEHPK3PXP&issuer=GitHub
JBSWY3DPEHPK3PXP is the secret, Base32-encoded. The service keeps a copy; your app keeps a copy. That's the whole "enrollment".
The algorithm in 10 lines
- Take the current Unix time and divide by 30 → a counter that changes every 30 seconds.
- HMAC-SHA1 the counter (8 bytes, big-endian) with the secret.
- Pick 4 bytes from the result using the last nibble as an offset ("dynamic truncation").
- Take that number mod 10^6 → your 6-digit code.
In the browser, with zero dependencies:
async function totp(secretBytes, now = Date.now(), period = 30, digits = 6) {
const counter = Math.floor(now / 1000 / period);
const msg = new ArrayBuffer(8);
new DataView(msg).setUint32(4, counter); // fine until year 2106
const key = await crypto.subtle.importKey('raw', secretBytes,
{ name: 'HMAC', hash: 'SHA-1' }, false, ['sign']);
const h = new Uint8Array(await crypto.subtle.sign('HMAC', key, msg));
const o = h[h.length - 1] & 15;
const bin = ((h[o] & 0x7f) << 24) | (h[o+1] << 16) | (h[o+2] << 8) | h[o+3];
return String(bin % 10 ** digits).padStart(digits, '0');
}
Same secret + same time = same code, on any device. No network needed.
So why is my code "wrong"?
- Clock drift. The counter comes from your device clock. If it's 30+ seconds off, you're computing the previous or next code. Most servers accept ±1 step, so a minute of drift breaks it.
- Wrong parameters. Some services use SHA256, 8 digits or a 60-second period. The QR code says so; a manually typed key doesn't.
- Typos in the key. Base32 has no 0, 1 or 8. An "O" vs "0" mix-up gives a valid-looking but wrong secret.
- Steam uses its own 5-character alphabet on top of the same HOTP value.
A tool if you just need the codes
I packaged this into Code2FA: paste a key (or hundreds of ID|Pass|2FA lines) or scan a QR code, and it shows live codes – computed in your browser, keys never uploaded. It also reads Google Authenticator export QR codes and has a "why is my code rejected?" checker that measures your clock.
The engine is open source (MIT, ~10 KB, all RFC 6238 test vectors pass): github.com/nguyennoben-a11y/code2fa-totp
Questions about TOTP edge cases? Ask in the comments.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.