Course contentsShow
← Security
Lesson 740 of 3,05216. Web Security - Authentication MechanismsFree lesson

TOTP and Time-Based One-Time Passwords

How TOTP generates time-synchronized codes using shared secrets and HMAC-SHA1, and implementing RFC 6238 correctly.

TOTP and Time-Based One-Time Passwords

What you'll learn: How TOTP generates secure, time-synchronized codes that expire every 30 seconds using shared secrets and cryptographic hashing.


What is TOTP?

TOTP (Time-Based One-Time Password) is a multi-factor authentication mechanism that generates temporary 6-8 digit codes that change every 30 seconds. Both the authentication server and your authenticator app (like Google Authenticator) use the same shared secret and the current time to independently generate identical codes.

Think of it like synchronized watches: if you and a friend set your watches to the exact same time and follow the same rule (like "add the current minute to a secret number"), you'll always get the same result without talking to each other.


How TOTP Works

TOTP follows RFC 6238 and builds on these components:

  1. Shared Secret: A random key exchanged during setup (usually as a QR code)
  2. Time Step: The current Unix timestamp divided by 30 seconds (creating 30-second windows)
  3. HMAC-SHA1: A cryptographic function that combines the secret and time step
  4. Truncation: Converting the HMAC output into a human-readable 6-digit code

The formula: TOTP = Truncate(HMAC-SHA1(SharedSecret, TimeStep))

Both client and server perform this calculation. If they produce the same code within the time window (often allowing ±1 step for clock drift), authentication succeeds.


Why TOTP is Secure

  • Time-limited: Each code expires in 30 seconds
  • Unpredictable: HMAC ensures codes can't be guessed from previous ones
  • Replay-resistant: Old codes become invalid immediately
  • Offline-capable: No network connection needed to generate codes

Key Takeaway: TOTP generates time-synchronized one-time passwords by applying HMAC-SHA1 to a shared secret and the current time window, creating short-lived codes that both client and server can independently verify without communication.