Mathematical Foundations of TOTP: Why Offline Generators Stay Synchronized Without Network State
Even in complete network isolation, two independent devices converge on the exact same 6-digit token every 30 seconds. Rather than transmitting runtime secrets, RFC 6238 reduces authentication to deterministic time quantization over a keyed Pseudorandom Function (PRF).
1. Formal Definition: Deterministic Shared Evaluation Instead of Runtime Messaging
Push-based OTP mechanisms (SMS or email) rely on out-of-band third-party transport during every login. By contrast, TOTP (IETF RFC 6238, extending RFC 4226 HOTP) exchanges one symmetric secret K during enrollment and requires zero communication during verification.
Given a shared Base32-decoded key K (minimum 128-bit recommended entropy), reference epoch T₀ = 0, and time-step duration X = 30s, any device tracking Coordinated Universal Time t independently evaluates:
T = ⌊ (t - T₀) / X ⌋ (encoded as 8-byte Big-Endian uint64)
HS = HMAC-H(K, T) (H ∈ {SHA-1, SHA-256, SHA-512})
offset = HS[|HS| - 1] & 0x0F (range [0, 15])
DT(HS) = ((HS[offset] & 0x7F) << 24)
| ((HS[offset + 1] & 0xFF) << 16)
| ((HS[offset + 2] & 0xFF) << 8)
| (HS[offset + 3] & 0xFF) (masking sign bit yields 31-bit integer S)
TOTP(K, t) = DT(HS) mod 10^d (d ∈ {6, 8}, zero-padded on left)- Key Entropy Bound: RFC 4226 §4 requires at least 128 bits of random entropy (160 bits recommended) so offline brute-force key search remains infeasible;
- UTC Frame Invariance: Because Unix epoch seconds depend on UTC rather than local timezones or carrier connectivity, identical inputs produce identical codes offline worldwide.
2. Byte-Level Implementation & Interactive Web Crypto Lab
Dynamic Truncation extracts a fixed-width positive integer while eliminating signedness discrepancies across CPU architectures and runtimes via the 0x7F MSB mask:
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');Interactive Lab: Watch RFC 6238 Compute Step by Step
---3. Security Reduction: Why Raw SHA-1 Collisions Do Not Break HMAC-SHA1 in TOTP
Public collision attacks on unkeyed SHA-1 (such as SHAttered) allow an adversary to construct two distinct files producing an identical digest—breaking collision resistance.
Within HMAC(K, m) = H((K ⊕ opad) || H((K ⊕ ipad) || m)), however, message m is merely a fixed 8-byte monotone counter T rather than adversary-crafted colliding prefix blocks, and K remains hidden. Bellare (2006) proved that HMAC security reduces solely to the pseudorandomness (PRF) of the underlying compression function—even when the unkeyed hash fails collision resistance. Recovering a high-entropy secret K from truncated 6-digit samples remains computationally infeasible.
| Dimension | HMAC-SHA1 (RFC 6238 Default) | HMAC-SHA256 / SHA-512 | Cryptographic Consensus |
|---|---|---|---|
| Security Assumption | Compression-function PRF (collision-resistance free) | Larger internal state & modern hash structure | Both remain secure against key recovery under short counter inputs |
| Single-Attempt Guess Odds | P = 1 / 10^d (10^-6 for 6 digits) | P = 1 / 10^d (10^-6 for 6 digits) | Online guessing requires strict verifier rate-limiting |
| Ecosystem Interoperability | Universal across public identity providers | Common in audited enterprise & custom SSO | Preserve SHA-1 compatibility while honoring explicit URI hash parameters |
4. Clock Skew Bounds & Monotonic Anti-Replay State Machines
- Bounded Skew Windows: Verifiers search [T - s, T + s] (typically s = 1 per RFC 6238 §5.2) to absorb typing delay and minor clock drift;
- Strict Monotonic Replay Prevention: Because a token remains mathematically valid for X seconds, verifiers must persist the last accepted counter T_last and enforce T_match > T_last atomically;
- RTC Drift Discipline: While zero runtime traffic occurs, devices still rely on periodic OS NTP time sync so hardware clock drift stays well inside ±s·X;
- Parameter Fidelity: Compliant engines honor non-default digits (6 or 8), custom periods (10–120s), and SHA-256/SHA-512 algorithms specified in otpauth:// URIs.
Core Mathematical Takeaways
- Offline TOTP equivalence relies on independent evaluation of HMAC-H(K, ⌊(t - T₀)/X⌋), eliminating runtime relay latency.
- Bellare (2006) proves HMAC security without hash collision resistance, preserving HMAC-SHA1 soundness for high-entropy shared secrets.
- Production security combines secret entropy >= 128 bits, bounded skew windows [T-1, T+1], and strict T_match > T_last anti-replay checks.
Standards & References
- IETF RFC 6238 — TOTP: Time-Based One-Time Password Algorithm: Specifies UTC time-step quantization, resynchronization bounds, and anti-replay state rules.
- IETF RFC 4226 — HOTP: An HMAC-Based One-Time Password Algorithm: Defines 8-byte Big-Endian counters, dynamic truncation DT(HS), and 128-bit secret requirements.
- IETF RFC 2104 — HMAC: Keyed-Hashing for Message Authentication: Defines the nested inner/outer pad keyed hash construction.
- Bellare (CRYPTO 2006) — New Proofs for NMAC and HMAC: Security without Collision-Resistance: Establishes HMAC PRF security without assuming collision resistance of the underlying hash.