How TOTP (Time-Based OTP) Works
Learn how Time-Based One-Time Passwords work under the hood. Understand the algorithm that powers Google Authenticator and other 2FA apps. Free browser-based guide.
Detailed Explanation
Understanding TOTP: The Algorithm Behind 2FA
TOTP (Time-Based One-Time Password) is the algorithm that powers most two-factor authentication apps, including Google Authenticator, Authy, and Microsoft Authenticator. Defined in RFC 6238, TOTP generates short-lived numeric codes that prove you possess a shared secret.
The Core Mechanism
TOTP works by combining two inputs:
- A shared secret key — a random value known to both the server and your authenticator app
- The current time — divided into fixed intervals (typically 30 seconds)
The algorithm computes an HMAC-SHA1 (or SHA-256/SHA-512) hash of the time counter using the secret key, then extracts a numeric code from the hash through a process called dynamic truncation.
TOTP = Truncate(HMAC-SHA1(secret, floor(time / period)))
Step-by-Step Breakdown
- Get the current Unix timestamp (seconds since January 1, 1970)
- Divide by the time period (default: 30 seconds) and take the floor — this is the time counter
T - Encode the counter as an 8-byte big-endian integer
- Compute HMAC using the shared secret and the counter bytes
- Dynamic truncation: extract 4 bytes from the HMAC at an offset determined by the last nibble
- Modulo reduction: reduce the 31-bit integer to the desired number of digits (e.g.,
mod 10^6for 6 digits)
Why It Works
Because both the server and your device share the same secret and use synchronized clocks, they independently generate the same code at the same time. The code changes every 30 seconds, so even if an attacker intercepts one code, it expires before they can reuse it.
Security Properties
- Codes are time-limited — valid only for the current window
- The secret is never transmitted after initial setup
- Each code is unpredictable without knowing the secret
- The algorithm is well-audited and standardized
Use Case
Understanding TOTP fundamentals is essential for developers implementing two-factor authentication in their applications. Whether you are building a login flow that accepts TOTP codes or debugging why codes from an authenticator app are being rejected, knowing how the algorithm works at each step helps you diagnose issues with time synchronization, secret encoding, and truncation parameters.