← All posts

How TOTP works: HOTP, RFC 6238 and the maths of 6-digit codes

28 Nov 2026 · 9 min read

How a six-digit code proves who you are: HOTP and TOTP from first principles, RFC 4226 and RFC 6238

Every authenticator app does the same small calculation: take a secret key and the current time, run them through HMAC, and squeeze the result into six digits. That calculation is TOTP, the time-based one-time password defined in RFC 6238. This post explains how TOTP works from first principles, shows a Python implementation that passes all 18 official test vectors, and does the brute-force maths that tells you how many wrong guesses you can afford to allow.

I wrote this while building dj-totp-2fa, my open-source two-factor package for Django. Everything below stands on its own, though: it is about the standards, not the package.

HOTP first: a counter, a key and HMAC

TOTP is a thin layer over an older algorithm, HOTP, from RFC 4226 (December 2005). HOTP has two inputs:

The definition is one line: HOTP(K, C) = Truncate(HMAC-SHA-1(K, C)). HMAC (RFC 2104) is a keyed hash: without K you cannot predict the output, and seeing outputs does not reveal K. HMAC-SHA-1 produces 20 bytes. The interesting part is how 20 bytes become six digits.

Dynamic truncation, step by step

HOTP pipeline using the RFC 4226 example: the last HMAC byte 0x5a gives offset 10, bytes 10 to 13 are 0x50ef7f19, masking the top bit gives 1,357,872,921, and modulo one million gives 872921.

Section 5.3 of RFC 4226 calls this "dynamic truncation":

  1. Take the low 4 bits of the last byte. That is a number from 0 to 15, the offset.
  2. Read the 4 bytes starting at that offset as a big-endian integer.
  3. Clear the top bit, leaving a 31-bit number. The RFC does this "to avoid confusion about signed vs. unsigned modulo computations" on different processors.
  4. Take that number modulo 10Digit. Digit must be at least 6; 7 and 8 are allowed.

The diagram uses the worked example from section 5.4: the last byte is 0x5a, so the offset is 10, the four bytes there are 0x50ef7f19, and 1,357,872,921 mod 106 is 872921. Because the offset comes from the hash itself, which 4 bytes get used changes every time.

One small detail: 231 is 2,147,483,648, which is not a multiple of a million. I checked: 231 mod 106 = 483,648, so codes 000000 to 483647 can each be produced by 2,148 of the 31-bit values and the rest by 2,147. That is a bias of about 0.05%. RFC 4226 analyses this and concludes the bias is negligible and that brute force remains the best attack.

From HOTP to TOTP: the counter becomes time

HOTP's weakness in practice is the counter. The token increments it on every button press, the server only on every successful login, so they drift apart and need resynchronising. TOTP (RFC 6238, section 4, May 2011) removes the stored counter and derives it from the clock:

T = floor((current_unix_time - T0) / X)
TOTP = HOTP(K, T)

The defaults are T0 = 0 (the Unix epoch) and X = 30 seconds. So at Unix time 59, T is 1; at 60, T is 2. The RFC also requires implementations to support T values beyond 32 bits, for dates after 2038. RFC 6238 additionally allows HMAC-SHA-256 and HMAC-SHA-512 in place of SHA-1.

Apps learn the key and parameters from a QR code. The widely used Key URI format (otpauth://totp/...) carries the secret in Base32 and has optional algorithm, digits and period parameters, with defaults SHA1, 6 and 30. That same page notes that Google Authenticator ignores some of those parameters, which is why most deployments stick to the defaults.

A TOTP implementation in Python, tested against RFC 6238

The whole algorithm fits in the standard library: hmac, hashlib and struct.

import hashlib
import hmac
import struct


def hotp(key: bytes, counter: int, digits: int = 6, algo: str = "sha1") -> str:
    msg = struct.pack(">Q", counter)                  # 8-byte big-endian counter
    mac = hmac.new(key, msg, algo).digest()
    offset = mac[-1] & 0x0F                           # low 4 bits of last byte
    code = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
    return str(code % 10 ** digits).zfill(digits)


def totp(key: bytes, unix_time: int, step: int = 30, t0: int = 0,
         digits: int = 6, algo: str = "sha1") -> str:
    return hotp(key, (unix_time - t0) // step, digits, algo)

I ran it on Python 3.14 against the RFC 4226 Appendix D values and all 18 rows of RFC 6238 Appendix B (8 digits, three hash functions, six timestamps). This is the real output:

HOTP: ['755224', '287082', '359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489']
         59  T=0000000000000001  sha1   94287082  ok
         59  T=0000000000000001  sha256 46119246  ok
         59  T=0000000000000001  sha512 90693936  ok
 1111111109  T=00000000023523EC  sha1   07081804  ok
 1111111109  T=00000000023523EC  sha256 68084774  ok
 1111111109  T=00000000023523EC  sha512 25091201  ok
 1111111111  T=00000000023523ED  sha1   14050471  ok
 1111111111  T=00000000023523ED  sha256 67062674  ok
 1111111111  T=00000000023523ED  sha512 99943326  ok
 1234567890  T=000000000273EF07  sha1   89005924  ok
 1234567890  T=000000000273EF07  sha256 91819424  ok
 1234567890  T=000000000273EF07  sha512 93441116  ok
 2000000000  T=0000000003F940AA  sha1   69279037  ok
 2000000000  T=0000000003F940AA  sha256 90698825  ok
 2000000000  T=0000000003F940AA  sha512 38618901  ok
20000000000  T=0000000027BC86AA  sha1   65353130  ok
20000000000  T=0000000027BC86AA  sha256 77737706  ok
20000000000  T=0000000027BC86AA  sha512 47863826  ok
18/18 vectors match

The ten HOTP values match RFC 4226 Appendix D exactly. Notice that 287082 (HOTP, counter 1) is also the last six digits of 94287082 (TOTP at T = 1): TOTP really is HOTP with a time-derived counter.

One trap. Appendix B says the test key is the ASCII string 12345678901234567890. That is only true for SHA-1. The Java reference code in Appendix A uses a 32-byte key for SHA-256 and a 64-byte key for SHA-512 (the same digits repeated). With the 20-byte key, my SHA-256 result at t = 59 was 32247374, not 46119246. This mismatch is reported as erratum 5132 (status "Reported" when I checked). If your SHA-256 vectors fail, check the key length first.

Clock drift and the validation window

A row of five 30-second time steps. T minus 1, T and T plus 1 are accepted; T minus 2 and T plus 2 are rejected. Notes: RFC 6238 recommends at most one step for network delay; store the last successful step and reject anything at or before it.

A code typed at second 29 of a step may arrive at the server in the next step, and phone clocks drift. RFC 6238 section 5.2 says the verifier should also check past steps within an acceptable delay, and "We RECOMMEND that at most one time step is allowed as the network delay." Section 6 adds resynchronisation: once a code matches at an offset, the server can record that drift for the token and apply it next time.

Most servers check a symmetric window of one step either side. That means three codes are valid at any moment, which matters for the brute-force maths below.

Replay protection: one code, one use

A 30-second code is valid for up to 30 seconds, plus the window. Anyone who sees it in that time (a shoulder-surfer, a phishing proxy) could reuse it. RFC 6238 is explicit: the verifier "MUST NOT accept the second attempt of the OTP after the successful validation has been issued for the first OTP". NIST SP 800-63B says the same: verifiers "SHALL accept a given OTP only once while it is valid".

The simplest way to do this is to store the last time step that succeeded and refuse any step at or before it:

def verify(key: bytes, code: str, now: int, last_step: int,
           window: int = 1, step: int = 30) -> int | None:
    """Return the matched time step, or None. Rejects steps <= last_step."""
    current = now // step
    for t in range(current - window, current + window + 1):
        if t <= last_step:
            continue                                   # replay: already used
        if hmac.compare_digest(totp(key, t * step), code):
            return t
    return None

Running it with a code from a phone whose clock is 30 seconds behind:

code from previous step: 081804
first use  -> 37037036
second use -> None
two steps old -> None

The code is accepted once, rejected the second time, and a code two steps old falls outside the window. hmac.compare_digest compares in constant time so the check does not leak how many digits matched. In a real system the "store last step" write must be atomic, or two simultaneous requests can both pass.

Brute-force maths: how many guesses can you allow?

RFC 4226 approximates an attacker's success as Sec = s·v / 10^Digit, where s is the number of codes accepted per attempt and v the number of attempts. For an exact figure, treat each guess as hitting one of s valid codes out of a million, independently: P = 1 − (1 − s/10^6)^N. I computed it in Python for s = 1 (current step only) and s = 3 (a ±1 window):

Line chart of the probability of guessing a 6-digit code against the number of wrong guesses on a log scale. With a plus or minus one step window: 0.03% at 100 guesses, 2.96% at 10,000, 25.9% at 100,000 and 95.0% at one million. With the current step only: 9.5% at 100,000 and 63.2% at one million.

Guesses Ns = 1s = 3 (±1 window)
1000.0100%0.0300%
1,0000.0999%0.2996%
10,0000.995%2.96%
100,0009.52%25.9%
1,000,00063.2%95.0%

With a ±1 window, an attacker reaches a 50% chance after about 231,049 guesses. Six digits are strong only if guessing is limited. That is why RFC 4226 requires throttling at the server, and says lockouts "MUST be across login sessions to prevent attacks based on multiple parallel guessing techniques". NIST SP 800-63B caps consecutive failures at no more than 100 before the authenticator is disabled, and explains the number as a balance against "100 attempts against a six-digit decimal OTP authenticator output". At that cap the chance is 0.03% with a ±1 window. Widening the window to ±2 makes s = 5 and every number above worse.

Storing the secret

Passwords can be hashed. TOTP secrets cannot: the server must recompute HMAC with the raw key every time it checks a code. So the key database is as sensitive as the users' phones. RFC 6238 recommends encrypting keys, decrypting them only when a code is verified, and limiting access to the processes that need them. It also says keys should be random and "of the length of the HMAC output", which is 20 bytes for SHA-1. NIST asks for at least 112 bits of security strength for the key. In Python, secrets.token_bytes(20) gives you 160 random bits.

In practice: generate keys with a cryptographic RNG, encrypt them at rest with a key kept outside the database, show the QR code once at enrolment, and give users recovery codes stored only as hashes.

Checklist

  • HMAC-SHA-1, 6 digits, 30-second steps, unless you control the authenticator app.
  • A 160-bit random secret, encrypted at rest.
  • A window of ±1 step at most.
  • Store the last accepted step and reject anything at or before it, atomically.
  • Rate-limit per account across sessions, well below 100 consecutive failures.
  • Test against RFC 4226 Appendix D and RFC 6238 Appendix B, with the right key lengths.

These are the defaults I chose for dj-totp-2fa. More of my work is on my portfolio. If you are adding two-factor authentication to a Django project and want a second pair of eyes, email me.

References

  1. D. M'Raihi et al., "HOTP: An HMAC-Based One-Time Password Algorithm", RFC 4226, IETF, December 2005. https://datatracker.ietf.org/doc/html/rfc4226
  2. D. M'Raihi et al., "TOTP: Time-Based One-Time Password Algorithm", RFC 6238, IETF, May 2011. https://datatracker.ietf.org/doc/html/rfc6238
  3. RFC Editor, Errata for RFC 6238 (erratum 5132, Appendix B test keys). https://www.rfc-editor.org/errata/rfc6238
  4. H. Krawczyk, M. Bellare, R. Canetti, "HMAC: Keyed-Hashing for Message Authentication", RFC 2104, IETF, February 1997. https://datatracker.ietf.org/doc/html/rfc2104
  5. NIST, Special Publication 800-63B, Digital Identity Guidelines: Authentication and Authenticator Management (SP 800-63-4 edition). https://pages.nist.gov/800-63-4/sp800-63b.html
  6. Google Authenticator project wiki, "Key Uri Format". https://github.com/google/google-authenticator/wiki/Key-Uri-Format
← How I run my portfolio and blog on Clou…
Offline-first web apps: caching, storag… →
Written by

Himal Dahal

CTO at Daleema Group. Backend developer in Kathmandu.

Get in touch