TOTP, the time-based one-time password algorithm, generates a short numeric code from a shared secret key and the current time, so that each code is valid only for a brief window, typically 30 seconds. In cybersecurity, and specifically in identity & access management, TOTP is one of the most widely deployed second factors in MFA, usually delivered through an authenticator app on a smartphone.
The algorithm is specified in RFC 6238 and builds directly on HOTP, the counter-based one-time password defined in RFC 4226. Its appeal lies in simplicity: the server and the device never need to communicate after enrollment, because both sides compute the same code independently from the same secret and a synchronized clock.
How TOTP derives a code from time
TOTP works by turning the current time into a moving counter and feeding that counter, together with the secret, into an HMAC function. The time step counter is calculated as the number of whole intervals elapsed since the Unix epoch, so with a 30-second step the counter increases by one twice per minute.
The computation then follows the HOTP procedure. The HMAC output, 20 bytes for HMAC-SHA-1, is reduced by dynamic truncation: the low four bits of the last byte select an offset, four bytes are read from that position, the top bit is masked, and the result is taken modulo 10^6 to produce a six-digit code. Leading zeros are preserved, which is why codes such as 004417 are valid.
The following table lists the parameters that define a TOTP configuration and their common values.
| Parameter | Common value | What it controls |
|---|---|---|
| Shared secret | 160 bits, Base32 encoded | Uniqueness and unpredictability of codes |
| Time step (X) | 30 seconds | How long each code remains current |
| Epoch start (T0) | Unix time 0 | Reference point for the counter |
| Hash algorithm | SHA-1 (SHA-256, SHA-512 optional) | HMAC primitive used for derivation |
| Code length | 6 digits (8 optional) | Guessing resistance per attempt |
Enrollment usually happens by scanning a QR code that encodes an otpauth://totp/ URI containing the secret, the issuer, the account label and optional parameters. Many authenticator apps silently ignore non-default settings, so in practice the six-digit, 30-second, SHA-1 profile is the only one that works reliably across apps.
Clock drift and validation windows
Because TOTP depends on time, clock synchronization between the server and the device is the main operational concern. Phones normally synchronize through network time, but drift, manual clock changes and network latency mean that a code typed near the end of its window may arrive after the server has moved to the next step.
Servers handle this with a validation window, accepting codes from one step before and one step after the current step. RFC 6238 recommends allowing at most one step of network delay. Some implementations also record the observed drift per user and adjust the expected counter, a technique called resynchronization.
The table below shows how the window size trades usability against security.
| Window setting | Codes accepted | Effective lifetime | Trade-off |
|---|---|---|---|
| Current step only | 1 | Up to 30 s | Strict, more user rejections |
| Plus or minus one step | 3 | Up to 90 s | Recommended balance |
| Plus or minus two steps | 5 | Up to 150 s | Tolerant, larger attack window |
| Wide drift tolerance | More than 5 | Several minutes | Weakens replay and guessing limits |
A server must also enforce one-time use: once a code has been accepted, the same code must be rejected for the rest of its window. Without this replay protection, an attacker who observes a code over the shoulder or in a log can reuse it within seconds.
TOTP compared with other second factors
TOTP sits in the middle of the assurance spectrum for second factors: stronger than SMS codes, weaker than phishing-resistant methods such as FIDO2 security keys and passkeys. The decisive difference is that a TOTP code is a shared secret typed by a human, so it can be relayed to a fake website just like a password.
The comparison below summarizes the main alternatives within the same Topic.
| Method | Phishing resistance | Network needed | Main weakness |
|---|---|---|---|
| SMS one-time code | None | Mobile network | SIM swapping and interception |
| HOTP | None | No | Counter desynchronization |
| TOTP | None | No | Real-time relay phishing |
| Push approval | Low | Yes | MFA fatigue attacks |
| FIDO2 or passkey | High | No | Recovery and device management |
TOTP also differs from HOTP in its failure mode. HOTP codes stay valid until used, which makes unused codes a lasting risk, while TOTP codes expire on their own. In exchange, TOTP requires a reliable clock, whereas HOTP only requires both counters to stay aligned.
Implementing TOTP securely
Secure TOTP deployment depends far more on secret handling than on the algorithm itself. The shared secret is effectively a password that never changes, so whoever obtains it can generate valid codes indefinitely. It must be generated with a cryptographically secure random number generator and stored server-side in encrypted form, not hashed, because the server needs the original value to compute codes.
Practitioners commonly apply the following controls.
- Encrypt stored secrets with a key held in a hardware security module or a managed key service.
- Apply rate limiting and account lockout, because a six-digit code allows one million combinations.
- Reject reused codes and log failed attempts for anomaly detection.
- Require the current code during enrollment to confirm that the device was set up correctly.
- Issue single-use recovery codes and protect the recovery path as strongly as the login itself.
Recovery deserves special attention. Many account takeover incidents bypass TOTP entirely by abusing a weak reset process, such as an email link or a support agent who removes the factor after a convincing phone call.
Limitations and common misconceptions
The most important limitation is that TOTP does not stop phishing. Adversary-in-the-middle toolkits proxy the real login page, capture the password and the code as the victim types them, and replay both within the validity window to obtain a session cookie.
The table below pairs frequent misunderstandings with the actual behavior.
| Misconception | Reality | Practical consequence |
|---|---|---|
| Codes cannot be stolen | Codes can be relayed in real time | Phishing-resistant factors are needed for high-risk accounts |
| The app needs internet access | Codes are computed offline | Works on aircraft and in remote locations |
| Secrets are hashed like passwords | Servers must store recoverable secrets | A database breach exposes every enrolled seed |
| SHA-1 makes TOTP broken | HMAC-SHA-1 remains sound for this use | Collision attacks on SHA-1 do not apply |
Other weaknesses are operational. Users who lose a phone without backups lose access, while apps that sync secrets to the cloud improve recovery but move the secret into another account that must itself be well protected.
The idea in brief
TOTP is the six-digit number that an authenticator app shows and replaces every half minute. When an account is set up, the website and the phone agree on a secret. After that, both use the secret and the current time to calculate the same number, without talking to each other.
It works like two synchronized watches with a hidden recipe. Knowing the password is no longer enough, because a thief also needs the phone. The main caution is that a fake website can still trick someone into typing the code, so the number should only ever be entered on the genuine site.
A practical scenario
A mid-sized accounting firm with 120 employees enables TOTP for its cloud email and document portal after several staff passwords appear in a credential-stuffing list. Each employee scans a QR code with an authenticator app, enters the current code to confirm enrollment, and stores ten printed recovery codes in a sealed envelope kept by the office manager.
The portal accepts codes from one step before or after the current step, blocks reuse, and locks the account for 15 minutes after five failed attempts. Over the next quarter, the security team sees hundreds of logins with correct passwords fail at the second step. No mailbox is compromised through stolen passwords, and the firm plans to move administrators to FIDO2 security keys to close the remaining phishing gap.