TOTP authentication secures user accounts by generating temporary numeric passcodes from a shared secret key and current time values [1]. Instead of transmitting static logins across open networks, a phone app computes a new six-digit code that expires after a brief window [3]. By synchronizing calculations through universal timestamps, both the user and the login server arrive at the same verification values independently [1].
How TOTP Authentication Works
The foundation of time-based security rests upon an open standard published by the Internet Engineering Task Force in May 2011 as RFC 6238. Published by D. M’Raihi of Verisign along with co-authors from Diversinet, Symantec, and Portwise, the specification was designed to secure enterprise Virtual Private Network (VPN) connections and authenticate users on wireless Wi-Fi networks. The algorithm extends the HMAC-based One-Time Password HOTP specification documented in RFC 4226 to support time as the active moving factor in TOTP authentication [1]. While the older system tracked sequential user actions through an incrementing counter, the newer variant uses time values instead [2]. This transition eliminated counter drift that often occurred when hardware tokens registered accidental button presses while disconnected from login servers [4].
The Initiative for Open Authentication OATH formed in 2004 as a vendor-neutral alliance to design royalty-free specifications, releasing HMAC-based One-Time Password HOTP under RFC 4226 before developing time-synchronized methods [8]. The consortium sought common primitives to replace expensive proprietary hardware tokens that hampered consumer adoption across online services [2]. D. M’Raihi led the authoring group for both foundational RFC specifications [1].
Under this shared cryptographic framework, security relies on a symmetric secret key established between the client token and the login server. By anchoring the moving factor to real-world clock intervals rather than manual button presses, the specification ensures that mobile devices and remote web servers arrive at identical passcodes without exchanging secrets across public networks [1]. Both endpoints run the same math [2].

Deriving Counters From Unix Time
In standard TOTP authentication deployments, the algorithm maps real-world clock time into an integer counter value known as T. The derivation calculates T by dividing the difference between current Unix time and an initial starting epoch by the time step interval [1]. The formula applies a mathematical floor function to ensure the calculation resolves into a discrete integer value [3].
The system standardizes on Coordinated Universal Time, tracking elapsed seconds from midnight UTC on January 1, 1970. The initial counter epoch T0 defaults to zero in standard configurations, while the time step parameter X defaults to 30 seconds. When the Unix clock reads 59 seconds, the division yields a counter value of one, but the moment the clock advances to 60 seconds, the integer value increments to two. The specification also mandates that software implementations accommodate counter values exceeding 32-bit integer limits when operating past the year 2038, preventing integer overflow failures on Unix systems [1].
Because counter steps advance automatically with the wall clock, software tokens do not need network access to compute valid passcodes [1]. The client phone reads its internal clock to calculate the current interval index [3]. Tokens compute offline [1].
Dynamic Truncation in HOTP
Once the time step value T is calculated, the token feeds both the shared secret key and the eight-byte counter into a keyed hash function [1]. RFC 4226 established HMAC-SHA-1 as the default hashing algorithm, producing a twenty-byte cryptographic digest [2]. RFC 6238 broadened this capability, permitting implementations to use HMAC-SHA-256 or HMAC-SHA-512 when higher digest lengths are required [1]. To transform this lengthy cryptographic hash into an accessible numeric string, the protocol applies a process called dynamic truncation [2]. Byte 19 gives the offset [4].
The algorithm examines the low-order four bits of the final byte in the hash result to determine an offset index between zero and fifteen. Starting at that specific offset byte, the extractor isolates a four-byte slice and masks out the most significant bit to yield 31 bits of unsigned data without sign bit ambiguity [4]. Mihir Bellare and David Naccache contributed to designing this step to eliminate mathematical discrepancies across differing microprocessor architectures [2]. The resulting 31-bit integer spans values up to 2,147,483,647, which equates to roughly 9.3 decimal digits of entropy [4]. Computing modulo 10^6 extracts the final six-digit decimal code [2].

If the modulo calculation produces a value shorter than six digits, the token prepends leading zeros to preserve uniform passcode length [4]. System designers can configure the output to return seven or eight digits by adjusting the modulo base to 10^7 or 10^8 [2]. While six digits remain the industry standard for consumer accounts, the underlying truncation math ensures identical distribution properties regardless of chosen output length [1].
Why Use TOTP Instead of SMS?
Online platforms deploy TOTP authentication instead of text messages because cellular transmission channels suffer from documented routing flaws [6]. When security teams compare symmetric time tokens to asymmetric browser mechanisms like how passkeys work in modern web browsers, both approaches avoid the hazards of telecom routing [7]. Text messaging routes authentication tokens across carrier networks that were never architected to provide confidential cryptographic transport [6].
In July 2016, David Meyer reported for Fortune that the National Institute of Standards and Technology moved to deprecate SMS-based two-factor authentication because telecommunications networks fail to provide robust data protection. Sophisticated attackers exploit structural flaws in the ancient SS7 signaling protocol or social engineer mobile carrier support desks to divert text messages onto attacker SIM cards during online account takeovers. Well-funded threat actors can even deploy IMSI-catcher hardware that mimics legitimate base stations to capture unencrypted wireless traffic from nearby devices [6]. The Verge highlighted these dangers when senior editor Richard Lawler faced fraudulent reset attempts against his Twitter account [7]. NIST drafted this ban in 2016 [6].
Local authenticator apps compute tokens without broadcasting radio signals or relying on active cell tower connectivity. Users traveling overseas or operating in underground facilities with no cellular coverage can still generate valid login codes reliably [7].

Provisioning Through QR Codes
Configuring client devices for TOTP authentication requires an initial exchange to share the secret key between the server and the user phone [1]. This enrollment exchange typically relies on a standardized Uniform Resource Identifier scheme beginning with otpauth://totp/. To simplify configuration on smartphones, the server encodes this URI into a Quick Response matrix barcode displayed during account setup. The label in the URI path identifies the user account, while query parameters convey key configuration values [3].
The shared key is transferred using Base32 encoding as specified in RFC 4648, with padding characters omitted to maintain compact barcode payloads. A token configuration might format as otpauth://totp/Wikipedian?secret=JBSWY3DPFQQHO33SNRSCC, where the Base32 string unpacks into the ASCII text Hello, world! on the phone. The URI query string may also declare the period parameter, defaulting to 30 seconds, with digit counts and the target hashing algorithm [3]. RFC 4226 recommends a shared secret length of at least 128 bits, while strongly advising 160 bits to match HMAC-SHA-1 output capacity [2]. Keys should be generated through cryptographically strong pseudorandom number generators properly seeded to prevent predictability [1].
Transmitting enrollment secrets requires encrypted browser channels, aligning with transport protections detailed in the TLS handshake key negotiation process to prevent eavesdroppers on public networks from intercepting raw shared keys [1]. If an adversary intercepts the barcode during enrollment, the attacker obtains the shared seed and can generate identical passcodes indefinitely [3].

Server Verification and Drift Windows
During TOTP authentication, when a user enters a six-digit code on a login portal, the authentication server evaluates the submission against its own system clock. Because client devices and remote servers experience network latency during transit across wide area networks, the packet arrival time rarely coincides perfectly with generation time. A phone clock may also drift slightly ahead or behind atomic time references over extended operating cycles [1]. RFC 4226 specifies a resynchronization parameter s to resolve small indexing differences between endpoints [2].
To accommodate latency without opening expansive attack vectors, RFC 6238 recommends an acceptable transmission delay window of at most one time step. Under this recommended delay window, the validation server checks the submitted code against time step T, T-1, and T+1, creating a ninety-second window that forgives slight clock skew without exposing broad attack surfaces. Expanding the validation envelope beyond one adjacent step increases exposure to eavesdropping and replay hazards, giving an attacker greater leeway to consume intercepted authentication codes [1]. Once a specific passcode is accepted within the window, the server marks that token as consumed to prevent replay attacks. Leslie Lamport introduced early one-time password concepts using iterative hash chains, but modern distributed web services rely on time synchronization to avoid storing long chains of one-time authorization codes [5].
Because six-digit tokens have only one million potential combinations, servers must enforce throttling rules to block brute-force guessing. RFC 4226 introduces parameter T to lock out accounts or inject delays after repeated authentication failures [2]. Without rate-limiting policies, automated tools could cycle through guesses within a single thirty-second window [4].
Where TOTP Authentication Falls Short
While TOTP authentication provides far better defense than static passwords, it does not provide absolute protection against sophisticated fraud. The main vulnerability stems from human interaction during the authentication workflow [3]. Because users manually copy and paste numbers into login fields, an adversary can position an automated man-in-the-middle proxy between the victim and the legitimate service. The Register reported as early as 2005 that phishing schemes actively targeted one-time passwords during online banking sessions [9].
In an automated adversary-in-the-middle attack, a fraudulent web proxy intercepts the user’s password and temporary passcode, immediately relaying them to the legitimate service to establish an unauthorized session before the thirty-second token expires. Because the symmetric secret lives in both the authenticator app and the company server database, a breach of the server key store also compromises all enrolled users [3]. Organizations seeking stronger protection against real-time credential theft increasingly evaluate asymmetric public-key credentials detailed in passkey authentication and cryptographic sign-ins to replace shared symmetric secrets entirely [7]. Furthermore, Defuse Security pointed out that conventional one-time passwords cannot encrypt stored user data across sessions, prompting proposals like Encrypted One Time Passwords EOTP as an alternative to S/KEY and Perfect Paper Passwords [10].

RFC 6238 recommends that validation databases protect shared keys using tamper-resistant hardware encryption and restrict access exclusively to authentication processes. Exposing keys in system memory should be limited to brief validation windows to minimize extraction hazards [1].
TOTP Authentication in Consumer Apps
Today, TOTP authentication serves as the core second-factor mechanism for major global platforms including Google, Amazon, Dropbox, Facebook, and Mastodon. Barbara Krasnoff reported for The Verge that while hardware tokens provide the highest security, mobile authenticator apps offer the most practical defense for consumer accounts on Amazon, Google, Dropbox, and Facebook. Users install software tools such as Google Authenticator, Microsoft Authenticator, or Authy to store shared secrets for multiple independent services on a single smartphone [7].
Hardware security keys manufactured by companies like Yubico YubiKey also support time-based one-time passwords with U2F and FIDO2 standards. These hardware tokens connect using USB-A, USB-C, Lightning, or Near Field Communication interfaces to compute codes inside tamper-resistant secure elements, exemplified by Yubico’s YubiKey 5C Nano. Apple supports physical security keys for Apple ID accounts running on iOS 16.3, iPadOS 16.3, or macOS Ventura 13.2 on a Mac, requiring users to register at least two separate keys to prevent accidental account lockout [7]. Hardware tokens avoid shared mobile operating system vulnerabilities, protecting the underlying secrets even if a user workstation suffers malware infection [5]. Major platforms also provide single-use backup recovery codes so account owners avoid permanent lockout if their primary device gets lost [7].
By standardizing on open RFC specifications, the Initiative for Open Authentication ensured that consumer security tools remain cross-compatible with different internet platforms. Users are never locked into a single software vendor or proprietary ecosystem [8].
- REPORT M’Raihi, D., Machani, S., Pei, M., & Rydell, J. (2011). TOTP: Time-Based One-Time Password Algorithm. Internet Engineering Task Force. [Article Link]
- REPORT M’Raihi, D., Bellare, M., Hoornaert, F., Naccache, D., & Ranen, O. (2005). HOTP: An HMAC-Based One-Time Password Algorithm. Internet Engineering Task Force. [Article Link]
- WEBSITE Wikipedia contributors. Time-based one-time password. Wikipedia, The Free Encyclopedia. [Article Link]
- WEBSITE Wikipedia contributors. HMAC-based one-time password. Wikipedia, The Free Encyclopedia. [Article Link]
- WEBSITE Wikipedia contributors. One-time password. Wikipedia, The Free Encyclopedia. [Article Link]
- ONLINE NEWS Meyer, D. (2016). Time Is Running Out For SMS-Based Login Security Codes. Fortune. [Article Link]
- ONLINE NEWS Krasnoff, B. (2023). How to set up two-factor authentication on your online services. The Verge. [Article Link]
- WEBSITE Initiative for Open Authentication. Open, Strong Authentication for Everyone. [Article Link]
- ONLINE NEWS Out-Law.com. (2005). Phishing attack targets one-time passwords. The Register. [Article Link]
- WEBSITE Defuse Security. (2026). Encrypting One Time Passwords [EOTP]. [Article Link]