Cryptography Spec · RFC 6238 8 min read Updated 2026-11-16

How TOTP Works Under the Hood: Why Offline Authenticators Match Remote Servers Down to the Second

Even inside Airplane Mode with zero network traffic, an authenticator generates 6-digit codes matching GitHub, AWS, and Google simultaneously. Here is the deterministic math, HMAC security model, and real-world systems engineering behind RFC 6238.

Device UTC Clock T = floor(Epoch / 30s) 0 Network Requests Base32 Secret K JBSW Y3DP EHPK 3PXP Exchanged Once via QR HMAC-SHA RFC 6238 & 0x7FFFFFFF Client & Server Identical Code 482 917 ✓ Instant Offline Match UTC Clock floor(t / 30s) Offline Epoch Secret Key K Base32 Vault Saved Once HMAC-SHA RFC 6238 + Truncate Exact Client / Server Match 482 917
RFC 6238 requires zero runtime communication: both sides compute identical HMAC digests from shared secret K and UTC step T

1. Core Architecture: Don't Transmit Codes—Solve the Same Equation Simultaneously

SMS and Email OTPs follow a push-delivery pattern: generate randomly on the server, push through external carriers or SMTP queues, and wait for the user to relay the value back.

TOTP (Time-based One-Time Password, IETF RFC 6238 extending RFC 4226 HOTP) flips this model completely. Once during initial QR pairing, the server shares one symmetric Base32 secret K (typically 80–160 bits of entropy) with the client. At login time, zero network messaging is required—both client and server rely solely on two deterministic inputs:

  • Shared Symmetric Secret (K): Decoded from the Base32 secret parameter inside an otpauth://totp/ URI;
  • Coordinated Universal Time (UTC Epoch): Any hardware RTC clock tracks elapsed seconds since 1970-01-01 00:00:00 UTC;
  • Because keyed HMAC functions are strictly deterministic, identical inputs yield identical codes on both ends with zero runtime network latency.
Shared Secret K Base32 -> 160-bit UTC Step T floor(t/30) [8B BE] HMAC-SHA SHA-1 / 256 / 512 20~64 Bytes Digest Dynamic Truncate offset = hmac[last] & 0x0f 4 Bytes & 0x7FFFFFFF S mod 10^6 482 917 100% Offline Token 1. Secret Key K Base32 -> Bytes UTC Step T floor(t/30) [8B] 2. HMAC-SHA (SHA-1 / 256 / 512) 20 ~ 64 Bytes Digest Output 3. Dynamic Truncation offset = hmac[last] & 0x0f 4 Bytes & 0x7FFFFFFF (31-bit) 4. S mod 10^6 -> Offline Instant Code 482 917
Animated Flow: Four-stage RFC 6238 deterministic pipeline (8-byte Big-Endian counter -> HMAC -> 4-bit offset truncation -> modulo output)

2. The 4-Stage Byte-Level Computation (Interactive Web Crypto Sandbox)

Every compliant implementation executes the exact same four operations defined by RFC 6238 and RFC 4226 §5.3:

  1. Quantize UTC Epoch into Step Counter T: Divide epoch seconds by period X (typically 30s) -> T = floor(unixSeconds / X), encoded as an 8-byte Big-Endian UInt64 buffer.
  2. Compute Keyed HMAC Digest: Hash that 8-byte buffer with decoded secret K via HMAC-SHA1, HMAC-SHA256, or HMAC-SHA512 to yield a 20-, 32-, or 64-byte MAC.
  3. Dynamic Truncation: Inspect the low 4 bits of the final digest byte (offset = hmac[len - 1] & 0x0f, range 0..15). Slice 4 consecutive bytes starting at offset, mask off the sign bit (& 0x7f) for cross-architecture integer uniformity, producing a clean 31-bit integer S.
  4. Decimal Modulo & Zero-Padding: Compute S mod 10^digits (1,000,000 for standard 6-digit tokens) and left-pad with zeroes.
Standard RFC 6238 Reference Implementation (Native Web Crypto API)
const counter = Math.floor(epochSeconds / period);
const counterBuffer = new ArrayBuffer(8);
new DataView(counterBuffer).setBigUint64(0, BigInt(counter), false);

const cryptoKey = await crypto.subtle.importKey(
  'raw', keyBytes, { name: 'HMAC', hash: hashName }, false, ['sign']
);
const hmacBytes = new Uint8Array(await crypto.subtle.sign('HMAC', cryptoKey, counterBuffer));

const offset = hmacBytes[hmacBytes.length - 1] & 0x0f;
const binary =
  ((hmacBytes[offset] & 0x7f) << 24) |
  ((hmacBytes[offset + 1] & 0xff) << 16) |
  ((hmacBytes[offset + 2] & 0xff) << 8) |
  (hmacBytes[offset + 3] & 0xff);
return (binary % Math.pow(10, digits)).toString().padStart(digits, '0');
⚡ Live Browser Web Crypto Sandbox

Interactive Lab: Watch RFC 6238 Compute Step by Step

30s · 6 Digits
Live 6-Digit TOTP Output
------ --s
1. UTC Counter: -
2. HMAC Digest: -
3. Truncate Offset: -

3. Why HMAC-SHA1 Remains Secure in TOTP Despite SHA-1 Collision Attacks

Publicized attacks against raw SHA-1 (like SHAttered) break collision resistance—allowing an attacker to craft two distinct documents with matching SHA-1 hashes.

In HMAC(K, m), however, the message m is merely an 8-byte monotone counter rather than attacker-crafted multi-block inputs, and key K remains secret. Cryptographic proofs (Bellare et al.) establish that HMAC relies on the pseudo-random function (PRF) property of its compression function rather than collision resistance. Recovering a high-entropy secret K from truncated 6-digit tokens remains infeasible.

Security AspectRFC 6238 (HMAC-SHA1)RFC 6238 (HMAC-SHA256 / SHA512)Engineering Consensus
Ecosystem AdoptionUniversal across public SaaS & cloud providersUsed in select enterprise/compliance setupsDefault SHA1 preserves compatibility while honoring URI config
Single-Attempt Guess Odds1 in 1,000,000 (6 digits)1 in 1,000,000 (6 digits)Server rate-limiting prevents online brute-force attempts
Key Recovery ResistanceInfeasible under random 80+ bit secret KHigher cryptographic marginProtecting local secret storage matters far more than hash choice

4. Four Production Systems Details Every Engineer Should Handle

  • Sliding Skew Window & Replay Rejection: Compliant verifiers validate [T-1, T, T+1] to tolerate typing/network lag, while strictly persisting the last accepted counter T_last so a submitted code cannot be replayed twice within the same 30s slot;
  • Boundary Lookahead UX: When <= 5 seconds remain in a cycle, pre-computing T + 1 in the UI eliminates the frustration of mistyping mid-transition;
  • System Clock Hygiene: Because devices compute T directly from local UTC epoch, keeping automatic OS network time enabled prevents step divergence across timezones or offline travel;
  • Strict URI Parameter Fidelity: Parsers should preserve non-default 8-digit formats, custom periods (e.g., 60s), and SHA-256/SHA-512 parameters verbatim.

Key Engineering Takeaways

  • TOTP trades runtime network messaging for deterministic shared computation over Secret K and UTC step T.
  • HMAC-SHA1 retains PRF security against key recovery even though unkeyed SHA-1 suffers from collision attacks.
  • Combining replay protection (T_last), bounded drift windows, and automated OS UTC sync yields a resilient authentication loop.

Looking for a Clean, Zero-Tracking RFC 6238 Authenticator?

Explore LazyCoffee — zero-knowledge encrypted sync across 7 platforms with local offline code generation.