# TOTP Authentication: HOTP Counters, Time Steps, and Safe Verification

> Implement RFC 6238 TOTP and RFC 4226 HOTP correctly: Base32 secrets, digit length, clock-skew windows, replay prevention, provisioning, recovery codes, and secret storage.

**Quick answer:** TOTP derives a one-time code from a shared Base32 secret and the current Unix time divided by a 30-second step; HOTP uses an incrementing counter instead. Verify only the current step and ±1, store the last accepted step to block replay, keep secrets encrypted, rate-limit attempts, and treat TOTP as one factor rather than the only one.

## Key takeaways

- HOTP is HMAC-SHA-1 over a moving counter, and TOTP derives that counter from Unix time divided by the period, so both sides need the same parameters and reasonably synchronized clocks.
- Base32 is an encoding, not encryption; the TOTP secret is a bearer credential that must be generated randomly, encrypted at rest, and never logged.
- Six digits is the interoperable default; eight digits lower the chance of a single guess, but rate limiting and lockout are the controls that actually stop brute force.
- Accept only the current step and one neighbor, record the matched step atomically, and reject any code whose step is not greater than the last accepted one.
- TOTP alone is possession only, so pair it with a password, prefer phishing-resistant authenticators for high-risk actions, and treat recovery codes as first-class credentials.

---

A one-time password is a shared secret plus an agreed clock. The server and the authenticator app derive the same short code from the same key at the same moment, and the server accepts that code once. The cryptography is deliberately simple; most TOTP incidents come from the operational edges instead: clocks that drift, secrets stored in plaintext, codes accepted twice, or verification windows widened until guessing becomes practical. This guide follows the code from RFC 4226 and RFC 6238 through enrollment, verification, storage, and proof.

## How HOTP counters and TOTP time steps produce a code

HOTP, defined in RFC 4226, computes an HMAC-SHA-1 over an eight-byte big-endian counter and the shared secret. Dynamic truncation then takes the low four bits of the final HMAC byte as an offset, extracts four bytes, clears the sign bit, and reduces the result modulo 10^digits. The counter increments with every code, so the verifier must remember the last counter it accepted for each token.

TOTP, defined in RFC 6238, removes the stored counter and derives it from time: the counter is the Unix time minus an epoch, divided by the period, floored. The conventional epoch is zero and the conventional period is 30 seconds. Both sides compute the same step only if their clocks agree, which makes time synchronization part of the authentication design.

```
K    = base32_decode(secret)
C    = floor(unix_seconds / 30)        # HOTP: stored counter, incremented per code
HS   = HMAC-SHA-1(K, C as 8-byte big-endian)
O    = HS[19] & 0x0f
code = ((HS[O..O+3] as uint32) & 0x7fffffff) % 10^digits
```

RFC 6238 permits SHA-1, SHA-256, and SHA-512, but SHA-1 remains the interoperable default because authenticator apps and provisioning URIs assume it unless told otherwise. The [HMAC generator](/tools/hmac) is useful for reproducing the intermediate value when you are debugging a failing test vector against a known secret, counter, and algorithm.

## Base32 secrets: encoding, length, and normalization

Authenticator apps exchange secrets as Base32, the RFC 4648 alphabet of A through Z and 2 through 7, normally without padding. A 160-bit secret, the size used by the RFC 4226 test vectors, is 20 bytes and therefore 32 Base32 characters. The string is an encoding, not a protection: anyone who sees it can generate valid codes forever.

Normalize before decoding, but do not guess. Strip spaces and lowercase letters, restore padding only for the decoder, and reject characters outside the alphabet instead of silently truncating. Base32 carries no checksum, so one mistyped character usually decodes to a different valid secret rather than raising an error; the only reliable proof is a code generated from the stored secret. That is why enrollment must verify a code before it activates the factor. The [Base32 encoder and decoder](/tools/base32) shows the exact alphabet and padding behavior, which helps when comparing what an app displays with what the database stored.

## Six digits or eight: choosing the code length

Six digits give one million possible values per step; eight digits give one hundred million. Neither number is a security boundary on its own, because an attacker who can submit unlimited guesses will exhaust either space. The real control is the number of attempts the verifier allows per account and per source. Six digits is the interoperable default and is adequate when throttling works; eight digits reduce the probability of a single random success and are reasonable when policy requires them and every client supports the larger code.

| Digits | Search space per step | Interoperability | Practical consequence |
| --- | --- | --- | --- |
| 6 | 1,000,000 | universal | standard choice; requires strict rate limiting |
| 8 | 100,000,000 | good but not universal | lower per-guess chance; must be declared in provisioning |

Leading zeros are part of the code. Treat codes as fixed-width strings, never as integers, or `002913` becomes `2913` and fails comparison. Digit count, algorithm, and period belong to the credential: changing any of them invalidates every enrolled authenticator.

## Clock skew and the plus-or-minus one step window

A phone clock can be tens of seconds off after a timezone change or a device that never synced. RFC 6238 recommends accepting one step before and one step after the current step when drift is expected. At a 30-second period that window spans three steps, or 90 seconds of server time; a code generated at the start of its step can stay acceptable for about 60 seconds, and one generated near the end for about 31.

The window is a tolerance, not a license. Widening it to four or ten steps to silence support tickets converts a clock defect into an authentication defect: every extra step increases both the guessing surface and the time in which a leaked code stays valid. Synchronize servers with NTP or chrony and monitor the offset. The [Unix timestamp converter](/tools/unix-timestamp) makes step boundaries concrete: divide the current epoch second by 30 and inspect the remainder to see how much of the step remains.

## Replay prevention: one successful code per time step

A TOTP code is valid for its whole step and, with a tolerance window, for neighboring steps as well. If the verifier only checks that the submitted code matches one of those steps, the same code can be submitted again and again until the window closes. A shoulder-surfed code, one captured by a phishing proxy, or one leaked in a screenshot then becomes reusable.

Record the matched step per user and factor, and update it atomically. Accept a code only when its step is strictly greater than the stored value, then write the new value in the same transaction, for example with a conditional update that affects one row or a Redis compare-and-set. A read-then-write sequence lets two concurrent requests carrying the same code both pass; the database must arbitrate. HOTP applies the same rule with the counter instead of the step. Clear the record when the factor is reset, and keep it out of caches that can roll back.

## Provisioning URIs, QR codes, and safe enrollment

Enrollment is usually a QR code containing an `otpauth://` URI. The canonical shape is `otpauth://totp/Issuer:account?secret=BASE32&issuer=Issuer&algorithm=SHA1&digits=6&period=30`. Percent-encode the label, keep the issuer prefix and the issuer parameter consistent, and declare algorithm, digits, and period explicitly instead of relying on defaults. Some apps ignore parameters they do not recognize, so test with the apps your users actually install.

The QR code is a secret in image form. Render it on an authenticated page, do not cache the response, do not put the URI in analytics or logs, and do not email it. Generate each secret with a cryptographically secure random source, one per user and factor, and never reuse a secret across accounts. Hold the new secret in a pending state, require a valid code before marking the factor active, and offer manual key entry when a camera or app fails. Enrollment without proof of a working code lets a bad scan lock the user out.

## Recovery codes and fallback authentication

Recovery codes are alternate authenticators and deserve the same care as the primary one. Generate eight to ten random codes with at least 128 bits of entropy each, show them once, and store only a hash. For truly random values a fast hash such as SHA-256 is sufficient; if codes are shorter or human-chosen, use Argon2id or bcrypt. Mark each code used atomically, never allow reuse, rate-limit redemption, and notify the account owner whenever one is redeemed.

Recovery must not become a weaker front door. A recovery code should complete the second factor, not reset the password or bypass identity verification for sensitive changes. Support-desk resets are the classic soft spot: if an attacker can talk past a weak identity check, TOTP is irrelevant. Require out-of-band identity proof, log every reset, and consider a delay or secondary approval for high-value accounts.

## Rate limiting, lockout, and online guessing

With unlimited attempts, a six-digit code falls in about a million guesses; ten attempts per second finishes in about a day, faster with a botnet. With five attempts per fifteen minutes per account, the same search takes years. Rate-limit by account, by source address, and by device fingerprint, apply exponential backoff, and return a generic failure that does not reveal whether the account exists or whether the code was close.

Lockout must be temporary and recoverable, or it becomes a denial-of-service tool: an attacker who knows a username can lock the owner out indefinitely. Prefer increasing delays, a challenge after a threshold, and alerting on per-account failure spikes. NIST SP 800-63B treats rate limiting as a requirement and sets a ceiling on consecutive failed attempts, so the policy should be written down and tested rather than left to a framework default. Log failures with enough context to investigate, but never log the submitted code or the secret.

## Secret storage, encryption, and rotation

The TOTP secret is a bearer credential: whoever holds it can mint valid codes indefinitely. Store it encrypted at rest with AES-256-GCM, using a per-record data key wrapped by a KMS, and bind the user and factor identifiers as associated data so a ciphertext cannot be moved between records. Keep encryption keys out of database backups, restrict decryption to the authentication service, and audit every access.

Rotation needs a plan before it is needed. Support two active secrets during a grace period when a user re-enrolls or a secret is suspected compromised, then revoke the old one. Re-encrypt under a new key version on a schedule, and test backup restoration. Never put a secret, an `otpauth://` URI, a generated code, or an HMAC intermediate into logs, error trackers, or analytics; those systems are usually readable by more people than the authentication database.

## Verification checklist and common mistakes

The expensive failures are known and testable:

| Mistake | Why it fails | Correct behavior |
| --- | --- | --- |
| Accepting a code twice | A captured code is replayed inside the window | Store the last accepted step and update it atomically |
| Widening the window to ±10 steps | Extends guessing and replay time | Accept the current step plus or minus one, and fix clocks instead |
| Using TOTP as the only factor | Possession alone is single-factor and phishable | Pair it with a password; prefer WebAuthn for high-risk actions |
| Logging secrets or provisioning URIs | Turns logs into a credential store | Redact secrets, codes, and URIs at the logger |
| Implementing custom crypto | Subtle truncation and comparison bugs | Use a maintained library with RFC test vectors |
| Comparing codes with `==` | Timing differences leak information | Use constant-time comparison |
| Unlimited attempts on six digits | A million guesses is a day of work | Rate-limit per account and per source |
| Storing secrets in plaintext | A database read becomes permanent account takeover | Encrypt with KMS-managed keys and restrict access |

Verify with the published vectors before trusting any implementation:

```
# RFC 4226 test vector: ASCII secret "12345678901234567890", counter 0
printf '12345678901234567890' | base32
# GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ

# HOTP counter 0 must print 755224
oathtool --hotp --base32 --counter 0 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ

# TOTP for the current 30-second step, six digits
oathtool --totp --base32 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ
```

A deployment passes only when every check below holds:

| Check | How to test | Pass criteria |
| --- | --- | --- |
| RFC vectors | Run RFC 4226 and RFC 6238 test vectors | HOTP counter 0 returns 755224; TOTP vectors match |
| Time step | Compare the server step with a known clock | Step equals floor(epoch/30); offset under one second |
| Skew window | Submit codes for T-2, T-1, T, T+1, and T+2 | Only the T-1, T, and T+1 codes are accepted |
| Replay | Submit a valid code, then submit it again | Second attempt rejected and logged |
| Provisioning | Scan the QR into two authenticator apps | Both generate identical codes for the same parameters |
| Leading zeros | Use a secret and step that produce `0xxxxx` | Code accepted as a fixed-width string |
| Rate limit | Exceed the per-account threshold | Backoff or temporary lockout, with no account enumeration |
| Storage | Inspect the database and backups | Ciphertext only, key material absent, access audited |
| Recovery | Redeem one recovery code twice | First succeeds, second fails, owner notified |
| Logs | Search logs for the secret and a code | No secret, URI, code, or HMAC intermediate appears |

The rules that keep TOTP safe are short. Derive the counter from a synchronized clock, accept only the current step and one neighbor, store the last accepted step atomically, and never let a code work twice. Treat the Base32 secret as a password-equivalent bearer token: encrypt it, restrict it, and never log it. Rate-limit verification, make lockout temporary, hash recovery codes, and use a maintained library rather than hand-rolled truncation. Finally, test the RFC vectors and the replay path on every release; a TOTP system that passes the happy path but accepts a code twice is worse than no second factor at all.

## Frequently asked questions

### Is TOTP by itself two-factor authentication?

No. TOTP proves possession of a shared secret, which is one factor. Two-factor authentication requires a second, independent factor such as a password or a passkey, so a login that asks only for a TOTP code is still single-factor.

### Why does a correct TOTP code get rejected?

The usual causes are a server or phone clock that has drifted, a secret with spaces or the wrong case, a mismatch in digits, period, or algorithm, or a code from a step outside the accepted window. Compare the server step against a synced clock, then confirm the provisioning parameters.

### Should I use six-digit or eight-digit codes?

Six digits is the interoperable default and is safe when verification is strictly rate-limited. Eight digits reduce the probability of a single random guess, but only if the authenticator and the provisioning URI agree; the digit count must never change silently.

### How do I stop the same TOTP code from being used twice?

Store the time step of every successful verification per user and compare it atomically. Accept a code only when its step is strictly greater than the stored value, update the value in the same transaction, and reject the second submission even though the code still matches.

### Where should TOTP secrets be stored?

Encrypt each secret at rest with an authenticated cipher and a key managed by a KMS, bind the record identifiers as associated data, restrict decryption to the authentication service, and never write secrets, provisioning URIs, codes, or HMAC intermediates to logs or analytics.

## References

- [RFC 6238: TOTP](https://www.rfc-editor.org/rfc/rfc6238)
- [RFC 4226: HOTP](https://www.rfc-editor.org/rfc/rfc4226)
- [NIST SP 800-63B](https://pages.nist.gov/800-63-4/sp800-63b.html)
- [OWASP: Multifactor Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Multifactor_Authentication_Cheat_Sheet.html)

---

- Canonical: https://www.jsonmind.com/guides/totp-authentication
- Locale: en
- Published: 2026-11-17
- Updated: 2026-11-17
- Tools: hmac, base32, unix-timestamp