Cryptographic Foundations · RFC 6238 8 min read Updated 2026-11-24

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).

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 evaluates the identical deterministic function TOTP(K, t) independently at both prover and verifier

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.
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
Four-stage deterministic RFC 6238 pipeline: 8-byte Big-Endian counter -> HMAC -> 4-bit truncation -> decimal modulo

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:

RFC 6238 Reference Implementation (W3C 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. 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.

DimensionHMAC-SHA1 (RFC 6238 Default)HMAC-SHA256 / SHA-512Cryptographic Consensus
Security AssumptionCompression-function PRF (collision-resistance free)Larger internal state & modern hash structureBoth remain secure against key recovery under short counter inputs
Single-Attempt Guess OddsP = 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 InteroperabilityUniversal across public identity providersCommon in audited enterprise & custom SSOPreserve 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.