security 7 min • Published 2024-10-01

How TOTP Two-Factor Authentication Works

A technical guide to Time-based One-Time Passwords (TOTP) — how 6-digit 2FA codes are generated, why they expire in 30 seconds, and how to implement RFC 6238.

What is TOTP?

Time-based One-Time Password (TOTP) is a two-factor authentication algorithm defined in RFC 6238. It generates a 6-digit code that changes every 30 seconds, derived from a shared secret key and the current Unix timestamp. Used by Google Authenticator, Authy, and Microsoft Authenticator.

How TOTP Codes Are Generated

1. A secret key (Base32-encoded) is shared between the server and authenticator app during QR code setup. 2. The current timestamp is divided by 30 (the time step T). 3. HMAC-SHA1 is computed over the time counter using the secret key. 4. A 4-byte dynamic truncation of the 20-byte HMAC output produces a 6-digit code. This is the TOTP algorithm.

Why 30 Seconds?

RFC 6238 specifies 30 seconds as the default time step (T=30). This balances security (short enough that intercepted codes expire quickly) and usability (long enough to type without rushing). Servers typically allow ±1 time step (±30s) to account for clock drift.

Security Considerations

TOTP codes are only valid for one time window. Never screenshot or share codes. The secret key must be stored securely — it is equivalent to a password. Use QR codes for setup (not manual entry when avoidable). Back up your secrets securely (encrypted backup of Base32 keys).

Try the Related Tools: