Skip to content

Lesson 2 of 9 · 24m

TOTP Internals: Secrets, Time Windows, and Replay Rules

How RFC 6238 actually works, how enrollment secrets must be stored, and the validation details that separate real TOTP from a demo.

TOTP looks simple: a six-digit code changes every thirty seconds. In production it is a shared-secret system with clock skew, enrollment risk, replay risk, and key-management obligations. Teams that treat it as a UI feature usually discover those obligations after an incident.

The algorithm is small and exact

TOTP is HMAC over a moving time counter, standardized in RFC 6238. The counter is usually floor(unix_time / 30), the secret is shared at enrollment, and the output is truncated to six or eight digits.

import base64, hashlib, hmac, struct, time

def totp(secret_b32: str, when: int | None = None, step: int = 30, digits: int = 6) -> str:
    key = base64.b32decode(secret_b32, casefold=True)
    counter = int((time.time() if when is None else when) // step)
    digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
    offset = digest[-1] & 0x0F
    value = struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7FFFFFFF
    return str(value % (10 ** digits)).zfill(digits)

SHA-1 appears in the spec for compatibility. This is not the broken use of SHA-1 people worry about in signatures; HMAC-SHA1 remains acceptable here, though SHA-256 is common in newer systems.

Enrollment is the dangerous moment

The authenticator enrollment URI is a secret. It usually looks like this:

otpauth://totp/SudoSecurity:traven@example.test?secret=JBSWY3DPEHPK3PXP&issuer=SudoSecurity&algorithm=SHA1&digits=6&period=30

Do not put that URI in logs, analytics events, support screenshots, or browser history if you can avoid it. Render the QR locally, expire incomplete enrollments, and require the user to prove possession by entering a valid code before marking the factor active.

Store the server-side secret encrypted at rest, ideally with the same key management as password reset tokens and session keys. A plaintext TOTP database is a password database with extra steps.

Validation has security rules

Validate the current step plus a small skew window, commonly one step before and one after. Rate-limit attempts aggressively: six digits are only one million possibilities, and online guessing becomes practical if you allow unlimited trials. Once a code succeeds for a login, do not accept the same code again in the same time step; otherwise a phished or shoulder-surfed code can be replayed inside thirty seconds.

Field notes

  • Clock skew is normal, but repeated large skew is a signal. Log it as telemetry, not as the secret or full code.
  • Never store 'the last correct code' in plaintext if you can store only its time-step fingerprint or counter metadata.
  • Eight digits reduce guessing pressure, but rate limiting still matters more than one extra digit or two.
  • TOTP is not phishing-resistant. A real-time proxy can relay the code before it expires.

Was this lesson helpful?

Sign in to rate