The Ultimate Guide to the Time-Based One-Time Password Algorithm
How the time-based one-time password algorithm turns a shared secret and the current time into a 6-digit code, how servers handle clock drift, and why TOTP still falls short against real-time phishing.
What is TOTP and How Does It Differ From HOTP?
The time-based one-time password algorithm is a cryptographic standard that generates a short, temporary numeric code — typically 6 digits — using nothing more than a shared secret key and the current time. No server call. No SMS. No internet connection required.
Quick answer: TOTP works like this:
- During setup, a server and your authenticator app share a secret key (once, securely).
- Every 30 seconds, both sides independently compute:
HMAC(secret, floor(Unix_time / 30)) - Both truncate the result to a 6-digit code.
- If the codes match, you're authenticated.
That's it. The elegance is in the symmetry — both sides arrive at the same code at the same time, without ever communicating during authentication.
Defined in RFC 6238 by the IETF in May 2011, TOTP is an extension of the earlier HMAC-based One-Time Password standard (HOTP, RFC 4226). The key difference: HOTP uses an incrementing event counter as its moving factor, while TOTP replaces that counter with a value derived from Unix time. Time moves forward predictably — and that predictability is what makes the algorithm work without any real-time coordination between client and server.
TOTP is now the backbone of most authenticator apps — Google Authenticator, Authy, Microsoft Authenticator — and is widely deployed across enterprise VPNs, cloud platforms, and web applications. A 2019 usability study found TOTP scored higher than other second factors tested, meaning it isn't just secure — users actually prefer it.
But TOTP is not without limits. Real-time phishing proxies, clock drift in hardware tokens, and a looming Year 2038 compatibility issue are real concerns for security engineers implementing it at scale.
This guide covers all of it: the math, the provisioning workflow, the server-side validation logic, the attack surface, and how TOTP stacks up against modern passwordless standards like FIDO2 and WebAuthn.
To understand the time-based one-time password algorithm, we must first look at its predecessor: the HMAC-based One-Time Password (HOTP) algorithm, defined in RFC 4226. Both algorithms rely on symmetric cryptography, meaning both the client (the user's device) and the server store an identical copy of a shared secret key.
The fundamental difference lies in the "moving factor" used to alter the generated password with each attempt.
HOTP is an event-based algorithm. Its moving factor is an 8-byte incrementing counter. Every time the user presses the button on a physical token or requests a code on an app, the client counter increments by one and generates a new code. When the user submits this code, the server checks it against its own counter. If the code matches, the server authenticates the user and increments its own counter to stay in sync.
However, this event-based design introduces a significant operational risk: counter desynchronization. If a user accidentally presses the button on their physical token multiple times while out of range of the server, the client-side counter will jump ahead. To handle this, validation servers must implement a "look-ahead window" that pre-computes the next several consecutive codes to find a match. If the counter gap exceeds this window, the token falls entirely out of sync, requiring a manual, out-of-band resynchronization process.
Furthermore, because HOTP codes do not automatically expire, an intercepted code remains valid indefinitely until it is used or until the counter moves past it. This makes HOTP more vulnerable to replay and interception attacks.
TOTP solves these issues by replacing the event counter with a time step derived from the current Unix time. Because time marches forward at the exact same rate on both the client and the server, the moving factor increments automatically without requiring any communication. This eliminates the counter desynchronization problem entirely for software authenticators, while restricting the lifespan of each generated code to a narrow window (usually 30 seconds).

Understanding these differences is key to choosing the right multi-factor authentication (MFA) strategy for your organization. For a deeper dive into how physical and digital tokens function in enterprise networks, read our guide on how OTP tokens strengthen enterprise authentication.
The technical differences between the two standards can be summarized as follows:
| Parameter / Feature | HOTP (RFC 4226) | TOTP (RFC 6238) |
|---|---|---|
| Moving Factor | Event-based incrementing counter | Time-based counter derived from Unix time |
| Code Expiration | Never (valid until used or counter advances) | Typically 30 to 60 seconds |
| Symmetric Key Storage | Required on both client and server | Required on both client and server |
| Primary Vulnerability | Interception and replay; counter desynchronization | Real-time phishing; clock drift in offline tokens |
| Supported Hashing Functions | Strictly HMAC-SHA-1 | HMAC-SHA-1, HMAC-SHA-256, HMAC-SHA-512 |
| Internet Requirement | None (fully offline) | None (fully offline) |
Cryptographic Mechanics of the Time-Based One-Time Password Algorithm
The core beauty of the time-based one-time password algorithm is that it produces a highly secure, short-lived token using basic cryptographic building blocks. Under the hood, the algorithm runs through a strict multi-step pipeline that transforms the current time and a shared secret into a human-readable numeric code.

This pipeline is standardized under RFC 6238. While the default implementation historically used HMAC-SHA-1 to match the original HOTP standard, the TOTP specification explicitly supports stronger, modern cryptographic hashing functions, including HMAC-SHA-256 and HMAC-SHA-512.
Regardless of the hashing function chosen, the algorithm always processes the inputs in two distinct phases: calculating the time-based counter, and then cryptographically hashing and truncating the result.
Mathematical Derivation of a TOTP Code
The moving factor in TOTP is an 8-byte integer $T$, which represents the number of time steps that have elapsed since the Unix epoch (midnight UTC on January 1, 1970). To calculate $T$, the algorithm uses three variables:
- Current Unix Time ($Unixtime$): The current system time expressed as the number of seconds elapsed since the Unix epoch.
- Initial Time ($T_0$): The starting point from which to count time steps. By default, this is set to 0 (the Unix epoch itself).
- Time Step ($X$): The duration of the time window in seconds. The recommended default is 30 seconds, which represents the optimal balance between user entry speed and security.
The formula to calculate the time step integer $T$ is:
$T = \lfloor \frac{Unixtime - T_0}{X} \rfloor$
The floor function (represented by the floor brackets) is critical here. It rounds the division down to the nearest whole integer. This ensures that for any given 30-second window, the value of $T$ remains completely static.
For example, if the current Unix time is 1,696,602,015 seconds:
$T = \lfloor \frac{1,696,602,015 - 0}{30} \rfloor = \lfloor 56,553,400.5 \rfloor = 56,553,400$
Fifteen seconds later, at Unix time 1,696,602,030:
$T = \lfloor \frac{1,696,602,030 - 0}{30} \rfloor = \lfloor 56,553,401.0 \rfloor = 56,553,401$
As you can see, the counter value $T$ incremented by exactly one when the clock crossed the 30-second boundary. This integer $T$ is then converted into an 8-byte byte array, padded with leading zeros, to serve as the message input for the HMAC function. For those interested in testing this math programmatically, you can explore our interactive one-time password generator to see how these inputs translate into real-time codes.
Dynamic Truncation and Modulo Reduction
Once the 8-byte counter value $T$ is computed, the algorithm feeds it and the shared secret key $K$ into the Hash-based Message Authentication Code (HMAC) function:
$HS = HMAC(K, T)$
The output $HS$ is a binary string. If HMAC-SHA-1 is used, the output is 20 bytes (160 bits) long. Because a 20-byte binary string is impossible for an end-user to quickly read and type into a login prompt, the algorithm performs "Dynamic Truncation" to extract a short, easily readable number.
Dynamic Truncation works through a clever, deterministic offset extraction process:
- Read the Last Byte: The algorithm looks at the very last byte (Byte 19 of the 20-byte HMAC output) and extracts its low-order 4 bits. This creates a value between 0 and 15, which serves as the "offset" index.
- Extract 4 Bytes: Starting at the offset index, the algorithm extracts 4 consecutive bytes from the HMAC output. For example, if the offset is 10, it pulls Bytes 10, 11, 12, and 13.
- Mask the Most Significant Bit: The first byte of this newly extracted 4-byte string is masked using a bitwise AND operation with
0x7f. This clears the most significant bit, converting the value into a signed 31-bit integer. This masking is essential to prevent signed/unsigned integer mismatch errors across different CPU architectures. - Modulo Reduction: The resulting 31-bit integer is converted to a decimal number. To reduce this large number to a standard 6-digit code, the algorithm performs a modulo operation against $10^6$ (or $10^8$ for an 8-digit code):
$OTP = BinaryCode \pmod{10^{Digit}}$
If the modulo operation produces a value with fewer than the requested digits, the algorithm pads the left side with leading zeros. This deterministic process ensures that both the client app and the validation server arrive at the exact same 6-digit code using only their local system clocks and the pre-shared key.
Provisioning and Server-Side Validation Workflows
For the time-based one-time password algorithm to function, the shared secret must be securely generated and distributed to the client device during onboarding. Once provisioned, the server must run a highly precise validation routine to handle real-world network latency and clock drift.

The onboarding flow relies on standard URI formatting and visual QR codes to eliminate manual entry errors, while the validation flow uses temporal tolerance windows to maintain a seamless user experience.
Client Onboarding and the otpauth URI Scheme
The provisioning process begins when a user enables MFA in their account settings. The server's identity provider generates a unique, cryptographically strong random secret key using a cryptographically secure pseudorandom number generator (CSPRNG) compliant with RFC 4086. This key is typically 16 to 32 characters long and is encoded in Base32 (RFC 4648) with padding omitted to make it easy to display and transmit.
To transfer this secret key to the user's authenticator app, the server constructs a specialized URI using the standard otpauth:// scheme. The URI contains all the configuration parameters the client app needs to generate matching codes:
otpauth://totp/EnterprisePortal:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=EnterprisePortal&algorithm=SHA1&digits=6&period=30
The parameters in this URI are highly structured:
- Type (
totp): Specifies that the client should use the time-based variant. - Label (
EnterprisePortal:user@example.com): Identifies the account name and provider, which helps users organize multiple accounts within their authenticator app. - Secret (
JBSWY3DPEHPK3PXP): The Base32-encoded shared secret key. - Issuer (
EnterprisePortal): Clearly identifies the organization provisioning the token to prevent identity confusion. - Algorithm, Digits, and Period: Optional parameters that define the hashing function, code length, and time-step size. If omitted, apps default to SHA-1, 6 digits, and a 30-second step.
The server encodes this entire URI into a QR code. The user simply opens their preferred authenticator app, scans the QR code, and the app automatically parses the URI and stores the shared secret securely. For a review of the top software authenticators capable of parsing these URIs securely, check out our guide on the best online authenticator app of 2026 for secure access.
Server-Side Validation and Clock Drift Mitigation
When a user attempts to log in, they enter their username, password, and the current 6-digit code displayed on their app. The validation server retrieves the user's encrypted shared secret from its database, decrypts it briefly in RAM, reads its own current system time, and calculates the expected TOTP code.
However, in the real world, system clocks are rarely in perfect alignment. Mobile devices may have slight clock skew, and network latency can delay the transmission of an authentication request. If a user submits a code at second 29 of a time step, the packet might not reach the server until second 31, when the server has already progressed to the next time step.
To prevent legitimate login attempts from failing, the validator must implement a tolerance window. Typically, the server computes and checks the TOTP codes for $T-1$ (the previous step), $T$ (the current step), and $T+1$ (the next step). This is known as a $\pm 1$ tolerance window, which allows for up to 30 seconds of clock drift or network delay in either direction.
While this tolerance window is essential for usability, it introduces a critical security risk: replay attacks. If an attacker intercepts a valid TOTP code within its 30-second window, they could attempt to reuse it. To mitigate this, the validation server must enforce a strict replay protection policy:
- Single-Use Tracking: The server must maintain a secure cache of successfully validated TOTP codes or the specific time-step index $T$ used for the login.
- Rejection of Duplicates: If a login request arrives with a code that has already been marked as used within the current time-step window, the server must immediately reject it.
- Drift Adjustment: Upon successful validation, the server can record the exact clock drift offset for that specific user's device. For physical hardware tokens (which suffer from incremental oscillator drift of about 2 minutes per year), the server can dynamically adjust its future validation windows for that token to keep them in sync.
For a comprehensive breakdown of implementing these validation rules securely across enterprise environments, refer to our one-time password token guide 2026.
Security Analysis: Strengths, Vulnerabilities, and Mitigations
The time-based one-time password algorithm remains a trusted, highly usable standard for securing user accounts, but its security profile is not uniform across all implementation models. As cyber threats have evolved, the differences between app-based TOTP and legacy MFA methods have become stark.

Understanding where TOTP excels — and where it fails — is critical for security engineers designing resilient identity and access management (IAM) architectures.
Why TOTP Outperforms SMS 2FA
For years, organizations relied on SMS-based verification codes as their primary second factor. However, SMS is now widely recognized as a high-risk authentication channel. Telecom networks rely on legacy protocols like Signaling System No. 7 (SS7), which are vulnerable to interception. Furthermore, attackers routinely bypass SMS protections using SIM-swapping attacks, where they socially engineer carrier customer service representatives into transferring a target's phone number to a rogue SIM card.
The time-based one-time password algorithm completely eliminates these vulnerabilities:
- No Carrier Reliance: TOTP codes are generated entirely locally on the user's device. No data is transmitted over cellular networks, making interception via SS7 or SIM-swapping impossible.
- Offline Capability: Because the algorithm relies only on the local system clock and the stored secret key, users can generate valid login codes even in areas with zero cellular reception or internet connectivity.
- Elimination of PII and Fees: Implementing TOTP removes the need to collect and store user phone numbers, reducing privacy compliance overhead. It also eliminates the ongoing carrier delivery fees associated with sending millions of SMS messages globally.
- Stronger Proof of Possession: A TOTP code can only be generated by a device physically holding the decrypted shared secret key, establishing a highly secure proof-of-possession factor.
For a deeper analysis of how TOTP acts as a core defense against modern credential-stuffing attacks, read our article on TOTP as a core method for modern authentication.
Key Vulnerabilities: Phishing, Clock Drift, and the Year 2038 Problem
Despite its advantages over SMS, TOTP is not a silver bullet. Security teams must account for three primary vulnerabilities:
1. Real-Time Reverse-Proxy Phishing
TOTP is not phishing-resistant. Modern phishing kits, such as Evilginx, utilize real-time reverse proxies. When a user lands on a spoofed login page, the proxy forwards their username and password to the legitimate site in real time. The legitimate site prompts for a TOTP code, which the proxy displays to the user. When the user enters their 6-digit code, the proxy captures it, submits it to the real server, and hijacks the authenticated session cookie. Because this entire process occurs within the 30-second validity window, the short lifespan of the TOTP code fails to protect the user.
2. Clock Drift in Hardware Tokens
Unlike mobile phones, which continuously synchronize their clocks via Network Time Protocol (NTP), physical hardware TOTP tokens rely on internal quartz crystal oscillators. These oscillators are subject to physical drift caused by temperature variations and aging, slipping by an average of 2 minutes per year. If a hardware token drifts beyond the server's look-ahead tolerance window, logins will fail. Servers must implement automatic resynchronization algorithms that dynamically track and record this drift on successful logins, or provide an out-of-band resynchronization portal.
3. The Year 2038 Problem
Unix time is traditionally stored as a signed 32-bit integer, which will overflow on January 19, 2038. When this occurs, systems relying on 32-bit integers will wrap around to 1901, causing the TOTP algorithm to calculate wildly incorrect time steps and rendering authentication completely non-functional. To prevent this, all modern TOTP implementations must support 64-bit integer time values to ensure long-term compatibility.
TOTP vs. Passwordless and Proximity-Based Authentication
As phishing attacks become more sophisticated, regulatory bodies and enterprise security teams are moving toward phishing-resistant multi-factor authentication. The most prominent standards driving this shift are FIDO2 and WebAuthn, which replace shared secrets with public-key cryptography.
Under FIDO2, there is no shared secret stored on a server. Instead, the user's device generates a unique cryptographic key pair for each website during registration. The private key remains securely locked inside the device's hardware enclave, while the public key is sent to the server.
During login, the server sends a cryptographic challenge, and the device signs it using its private key. This signature is verified by the server using the stored public key.
The critical security advantage of WebAuthn is "domain binding." During authentication, the browser automatically appends the origin domain of the website to the cryptographic challenge. If an attacker attempts to proxy the connection through a spoofed domain (e.g., login.company-security.com instead of login.company.com), the authenticator detects the mismatch and refuses to sign the challenge. This makes FIDO2 and WebAuthn completely immune to reverse-proxy phishing attacks.
However, transitioning an entire enterprise to passwordless WebAuthn can be challenging. It requires modern browser support, compliant hardware, and complex account recovery workflows if a user loses their primary device. Because of this, many organizations use a hybrid approach: deploying phishing-resistant FIDO2 keys for high-risk administrators, while keeping app-based TOTP as a highly secure, cost-effective backup factor for the broader workforce.
To bridge this gap, proximity-based authentication systems offer a unique alternative. For example, EveryKey provides a physical, proximity-based hardware-bound credential manager that automatically logs users into their workstations and web applications when they are nearby, locking the devices when they walk away. This approach combines the convenience of passwordless access with robust, hardware-backed security, reducing the reliance on manual code entry.
Frequently Asked Questions about TOTP
Does TOTP require an internet connection to generate codes?
No, TOTP does not require an internet connection, cellular reception, or any network connectivity on the client device. Because the algorithm relies entirely on the local system clock and the pre-shared secret key stored securely on the device, it can generate valid 6-digit codes in completely offline environments, such as airplanes, secure basements, or remote locations.
How do servers handle clock drift in TOTP authenticators?
Validation servers handle clock drift by implementing a tolerance window, typically checking the expected TOTP codes for the current time step as well as the immediately preceding and succeeding steps ($\pm 1$ time step). For physical hardware tokens that drift progressively over time, servers can run resynchronization routines that calculate drift offsets during successful logins and store those offsets to adjust future validation checks for that specific token.
Is TOTP completely secure against modern phishing attacks?
No, TOTP is not secure against modern, real-time reverse-proxy phishing attacks. If an attacker tricks a user into entering their credentials and TOTP code on a spoofed website, a reverse-proxy tool (like Evilginx) can capture the 6-digit code and submit it to the legitimate server in real time, successfully establishing an authenticated session before the code expires. To defend against this, organizations must transition toward phishing-resistant standards like FIDO2/WebAuthn.
Where TOTP Fits in a Modern Authentication Stack
The time-based one-time password algorithm (RFC 6238) remains one of the most successful and widely adopted security standards in the history of identity and access management. By transforming a shared secret and Unix time into a simple, rotating 6-digit code, it provides a highly effective defense against credential stuffing, brute-force attacks, and legacy telecom exploits like SIM swapping.
However, as reverse-proxy phishing kits become more accessible to low-skilled threat actors, relying solely on shared-secret MFA is no longer sufficient for high-security environments. Forward-thinking organizations should view TOTP as a highly reliable, offline-capable baseline, while actively planning their migration toward phishing-resistant passwordless architectures.
For more information on how to design, deploy, and secure modern authentication systems, explore our extensive library of technical resources and guides on TOTP as a core method for modern authentication.
