Back to all terms
Authentication
Authintermediate

TOTP (Time-Based One-Time Passwords)

A one-time password algorithm that generates short-lived codes based on a shared secret and the current time, commonly used as a second authentication factor.

Also known as: TOTP, Time-Based OTP, Authenticator App Codes, RFC 6238

Description

Time-Based One-Time Passwords (TOTP) is an algorithm defined in RFC 6238 that generates a short numeric code (typically 6 digits) from a shared secret key and the current timestamp. The code changes at a fixed interval, usually every 30 seconds. Both the authentication server and the user's device (typically an authenticator app like Google Authenticator, Authy, or 1Password) independently compute the same code using the shared secret and current time, enabling verification without transmitting the secret.

The algorithm works by dividing the current Unix timestamp by the time step (30 seconds), producing a counter value. This counter is combined with the shared secret using HMAC-SHA1 (or SHA-256/SHA-512) and dynamically truncated to produce the numeric code. The shared secret is typically a 160-bit (20-byte) random value, encoded in Base32 and exchanged during enrollment via a QR code containing an otpauth:// URI. The URI includes the issuer name, account identifier, algorithm, digits, and period parameters.

Server-side validation should accept codes from a small time window (typically the current step plus or minus one step) to account for clock drift between the server and the user's device. To prevent replay attacks, the server must track the last successfully used time step for each user and reject codes from the same or earlier steps. TOTP secrets must be stored encrypted at rest, and the enrollment QR code should only be displayed once. Implement rate limiting on TOTP verification attempts to prevent brute-force attacks on the 6-digit code space (1 million possibilities).

Prompt Snippet

Implement TOTP (RFC 6238) with the otplib or speakeasy library. Generate 20-byte secrets encoded in Base32, store encrypted with AES-256-GCM using a KMS-managed key. Present enrollment via otpauth:// URI in a QR code (qrcode library). Validate with a window of 1 step (+/- 30 seconds). Track last_used_counter per user to prevent replay -- reject any counter <= last used. Rate-limit verification attempts to 5 per minute per user. Support SHA-1 (default for compatibility with Google Authenticator) and SHA-256 for newer authenticators.

Tags

totpotpmfaauthenticatortime-basedrfc-6238