Time-Based One-Time Password (TOTP) is a widely adopted multi-factor authentication mechanism that generates temporary, time-synchronized codes on a user's device. TOTP provides a second authentication factor by requiring users to prove possession of a physical device (smartphone, hardware token) in addition to their primary credential (password or other first factor).
TOTP is defined in RFC 6238 and builds upon HMAC-based One-Time Password (HOTP) defined in RFC 4226. Unlike static passwords, TOTP codes expire every 30 seconds, making them resistant to replay attacks and significantly more secure than password-only authentication.
Before TOTP and multi-factor authentication became widespread, user accounts relied solely on passwords for security. This single-factor approach created critical vulnerabilities:
Password Reuse: Users often reuse passwords across multiple services, meaning a breach at one service compromises accounts elsewhere.
Phishing Attacks: Attackers could steal passwords through social engineering, and those credentials remained valid indefinitely.
Credential Stuffing: Stolen password databases enabled automated attacks against multiple services.
Weak Passwords: Users frequently chose weak, easily guessable passwords for convenience.
TOTP addresses these issues by adding a second factor that requires physical possession of a device. Even if an attacker steals a user's password, they cannot authenticate without also accessing the user's authenticator device. This dramatically reduces the risk of account compromise from password-related attacks.
TOTP implements the security principle of "something you know" (password) plus "something you have" (authenticator device). This combination ensures that authentication requires both knowledge and physical possession, making unauthorized access significantly more difficult.
Something You Know: The user's password or other primary credential that can be memorized.
Something You Have: The physical device (smartphone, hardware token) that generates TOTP codes.
Time Synchronization: Both the authentication server and the user's device must have reasonably accurate clocks to generate matching codes.
TOTP is explicitly designed as a second authentication factor, not a standalone authentication method. While TOTP codes prove device possession, they don't establish identity on their own. TOTP must always be combined with a primary authentication factor.
Valid Primary Factors for TOTP:
Why TOTP Requires a First Factor: TOTP codes rotate every 30 seconds and are generated algorithmically from a shared secret. Without a first factor to establish identity, anyone with access to the shared secret could generate valid codes. The first factor ensures that only the legitimate account owner can proceed to the TOTP verification step.
A complete TOTP authentication flow consists of two distinct phases:
Phase 1: Primary Authentication
Phase 2: TOTP Verification
TOTP generates one-time passwords through a cryptographic process involving a shared secret, the current time, and HMAC-SHA1 hashing.
Step-by-Step Process:
Mathematical Representation:
Time Step = floor(Unix Timestamp / 30)
HMAC Result = HMAC-SHA1(Secret Key, Time Step)
Offset = Last 4 bits of HMAC Result
Code Bytes = 4 bytes from HMAC Result starting at Offset
Code = (Code Bytes as Integer) mod 1,000,000
The shared secret is the cryptographic key that both the authentication server and the user's authenticator app must possess to generate matching codes.
Secret Key Properties:
Security Considerations:
TOTP relies on time synchronization between the server and the authenticator device to generate matching codes.
Time Window: Most implementations accept codes from the current time step as well as one step before and one step after (±30 seconds) to account for:
Synchronization Tolerance:
Handling Clock Skew: Systems can track successful authentication patterns to detect and compensate for consistent clock drift on specific devices.
Setting up TOTP authentication requires securely sharing the secret key between the authentication server and the user's authenticator app.
Server-Side Setup:
Client-Side Setup:
TOTP configuration uses the otpauth:// URI scheme for standardized QR code generation.
URI Structure:
otpauth://totp/Issuer:[email protected]?secret=BASE32SECRET&issuer=Issuer&digits=6&period=30
URI Components:
Protocol: otpauth://totp/ - Indicates TOTP protocol (not HOTP)
Label: Issuer:[email protected] - Display name in authenticator app
Issuer:AccountIdentifierParameters:
secret: Base32-encoded shared secret (required)issuer: Service name matching the label prefix (required)digits: Code length, typically 6 (optional, default: 6)period: Time step in seconds (optional, default: 30)algorithm: Hash algorithm (optional, default: SHA1)Example:
otpauth://totp/MyApp:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=MyApp&digits=6&period=30
TOTP secrets use Base32 encoding (RFC 3548) to make them human-readable and manually enterable if QR code scanning isn't available.
Base32 Characteristics:
Character Set: ABCDEFGHIJKLMNOPQRSTUVWXYZ234567 (32 characters)
Padding: Uses = characters for padding, though many implementations omit padding
Example Encoding:
01001000 01100101 01101100 01101100 01101111 (Hello)JBSWY3DPEBLW64TMMQ======Advantages Over Base64:
Phishing Attacks: Attackers may create fake login pages to capture both passwords and TOTP codes. However, TOTP codes expire quickly (30 seconds), limiting the window for successful phishing.
Man-in-the-Middle Attacks: If communications aren't encrypted with TLS, attackers could intercept TOTP codes. Always require HTTPS for authentication endpoints.
Secret Key Compromise: If the shared secret is exposed, attackers can generate valid codes indefinitely. Secrets must be:
Social Engineering: Attackers may trick users into revealing TOTP codes through phone calls or fake support requests. User education is critical.
Device Theft: If an attacker physically steals the user's authenticator device, they can generate codes. This risk is mitigated by device-level security (PINs, biometrics) and proper use of recovery codes.
Recovery codes provide a fallback authentication method when users lose access to their TOTP authenticator device.
Recovery Code Properties:
Recovery Flow:
Best Practices:
Rate limiting is essential to prevent brute-force attacks against TOTP codes.
Implementation Strategies:
Per-Account Limiting: Limit verification attempts per user account
Per-IP Limiting: Limit verification attempts from a single IP address
Progressive Delays: Increase delay between attempts after failures
Account Lockout: Temporarily disable TOTP verification after excessive failures
The time window for accepting TOTP codes represents a security trade-off between usability and security.
Standard Window (±1 step / 90 seconds total):
Strict Window (0 steps / 30 seconds total):
Lenient Window (±2 steps / 150 seconds total):
Clock Skew Tracking: Advanced implementations track which time window codes come from and adjust for consistent device clock drift.
Secret Generation:
1. Use cryptographically secure random number generator
2. Generate 20 bytes (160 bits) of random data
3. Encode using Base32 for storage and display
4. Never reuse secrets across accounts
Secret Storage:
1. Encrypt secrets at rest using AES-256 or similar
2. Use separate encryption keys for different data types
3. Rotate encryption keys periodically
4. Never log or display secrets after initial setup
5. Use parameterized queries to prevent SQL injection
Code Verification:
1. Retrieve and decrypt user's shared secret
2. Calculate current time step
3. Generate codes for current, previous, and next time steps
4. Compare user-provided code against all three using constant-time comparison
5. Track which time window was used for clock skew compensation
6. Invalidate codes immediately after successful use (if implementing single-use codes)
7. Implement rate limiting before verification
8. Log verification attempts (success and failure)
Security Headers:
1. Require TLS 1.2+ for all authentication endpoints
2. Implement Content-Security-Policy headers
3. Use Strict-Transport-Security (HSTS)
4. Enable X-Frame-Options to prevent clickjacking
5. Implement X-Content-Type-Options: nosniff
Authenticator App Selection: Recommend established, well-audited authenticator apps:
QR Code Display:
1. Generate QR code at appropriate resolution (300x300px minimum)
2. Display QR code only over HTTPS
3. Include manual entry option for accessibility
4. Clear QR code from DOM after successful setup
5. Never store QR code images on server
User Experience:
1. Provide clear setup instructions with screenshots
2. Test code verification immediately after setup
3. Display recovery codes prominently before completing setup
4. Require user acknowledgment of recovery code storage
5. Provide "Use recovery code" option on login screen
6. Allow TOTP reset with proper identity verification
Unit Tests:
1. Test code generation with known secrets and timestamps
2. Verify time window acceptance (±1 step)
3. Test Base32 encoding and decoding
4. Validate QR code URI generation
5. Test rate limiting logic
6. Verify recovery code generation and validation
Integration Tests:
1. Test complete registration flow
2. Test complete authentication flow
3. Test recovery code usage
4. Test TOTP reset process
5. Test account lockout scenarios
6. Test concurrent authentication attempts
Security Testing:
1. Attempt brute-force attacks against rate limiting
2. Test timing attack resistance
3. Verify secret encryption at rest
4. Test TLS configuration
5. Attempt replay attacks with expired codes
6. Test recovery code single-use enforcement
Many high-security applications require TOTP setup as part of the registration process.
Registration Flow:
Benefits:
Applications may allow existing users to optionally enable TOTP for enhanced security.
Enablement Flow:
Considerations:
Organizations may use TOTP as a step-up authentication requirement for sensitive operations.
Step-Up Flow:
Use Cases:
Native mobile applications can implement TOTP authentication with enhanced user experience.
Mobile Considerations:
TOTP Advantages:
SMS Advantages:
Recommendation: Use TOTP for security-critical applications; SMS OTP is acceptable for lower-risk scenarios but should not be considered strong MFA.
TOTP Advantages:
Email OTP Advantages:
Recommendation: Email OTP is suitable as a first factor (passwordless authentication). TOTP provides stronger security as a second factor.
TOTP Advantages:
Push Notification Advantages:
Recommendation: Push notifications provide better UX but require more infrastructure. TOTP is more universally compatible and works offline.
TOTP Advantages:
Hardware Key Advantages:
Recommendation: Hardware keys provide the strongest security (FIDO2/WebAuthn). TOTP is an excellent balance of security and usability for most applications.
Production TOTP implementations should fully comply with RFC 6238:
Required Parameters:
Implementation Notes:
NIST SP 800-63B Guidance:
PCI DSS Compliance:
SOC 2 Considerations:
Symptoms: Valid codes consistently rejected, user frustration
Solutions:
Symptoms: User cannot access account, lost phone/device
Solutions:
Symptoms: Users cannot scan QR code, poor camera quality
Solutions:
Symptoms: User enters code but authentication fails
Common Causes:
Solutions:
While SHA1 is currently standard for TOTP, the industry is gradually moving toward stronger hash algorithms.
Migration Path:
TOTP can serve as the second factor in passwordless authentication flows.
Passwordless + TOTP Flow:
This approach combines "something you have access to" (email) with "something you have" (authenticator device) for strong passwordless MFA.
Modern applications may offer both TOTP and WebAuthn (FIDO2) for maximum flexibility.
Dual Support Benefits:
Implementation:
TOTP authentication provides a proven, standardized approach to multi-factor authentication that balances strong security with practical usability. By requiring physical device possession in addition to primary credentials, TOTP significantly reduces the risk of account compromise from password-related attacks.
Successful TOTP implementation requires attention to several key areas: secure secret generation and storage, proper time window handling, comprehensive recovery mechanisms, and thoughtful user experience design. Following RFC 6238 standards and security best practices ensures interoperability with standard authenticator apps while maintaining strong security postures.
While newer authentication methods like WebAuthn offer advantages in specific scenarios, TOTP remains highly relevant due to its broad compatibility, offline functionality, and proven security track record. Organizations should consider TOTP as a core component of their authentication strategy, either as a standalone MFA solution or as part of a broader authentication framework supporting multiple factors and methods.