Frontegg.ai is now available in Beta Get started
Blog

What Is a Time-Based One-Time Password (TOTP)?

Time-Based One-Time Password (TOTP)

A time-based one-time password (TOTP) is a temporary passcode generated using the current time and a secret key known only to the user and the server. The combination makes TOTPs a secure method, minimizing risks of password reuse and theft when used in authentication. 

Unlike static passwords, TOTPs expire after a short duration, typically around 5 minutes depending on the level of risk of the scenario, improving security by reducing the window of opportunity for attackers to use a stolen code. TOTPs are widely adopted in two-factor/multi-factor authentication (2FA/MFA) processes, often delivered through mobile apps like Google Authenticator and Authy. 

These applications generate a new TOTP every fixed interval, requiring users to enter the code along with their other authentication factor. This dual-layer security ensures that even if the password is compromised, unauthorized access is thwarted without the passcode.

In this article:

The evolution of one-time passwords 

One-time passwords (OTPs) emerged as a response to the vulnerabilities of traditional static passwords, which are often unreliable as secrets because they are reused, shared, or susceptible to phishing and brute force attacks. Early implementations of OTPs relied on hardware tokens, which might’ve displayed numeric codes that changed periodically. These tokens provided a layer of dynamic authentication, but they were costly to manufacture and distribute.

Over time, advancements in cryptographic algorithms and widespread adoption of mobile devices shifted OTP generation to software-based methods. Event-based OTPs (such as those used in the HMAC-based one-time password, or HOTP, algorithm) marked an early step in this transition. These codes are generated based on a counter that increments with each authentication attempt, offering improved flexibility by removing reliance on physical, hardware tokens.

The development of Time-based OTPs (TOTPs) further improved upon HOTP by eliminating the need for user action to increment counters. By basing the code on synchronized time intervals, TOTPs aligned naturally by relying on a mutually used thirdd party resource that was pretty reliable because it played a key role in many other security and computer scenarios. This innovation, coupled with the growing availability of mobile apps capable of generating TOTPs, allowed for widespread, cost-effective adoption of strong two-factor authentication solutions.

How TOTPs work 

The TOTP algorithm explained

The TOTP algorithm combines a moving factor of time with a secret shared key to produce a one-time password. Often, the time component is the number of seconds since an epoch, divided by a predetermined interval (e.g., 30 seconds). This time is converted into a moving factor, providing a predictable yet temporary basis for generating codes. 

A cryptographic hash function, e.g., SHA-1, takes this moving factor along with the shared secret key to produce a hash that can be further converted into a short numeric code, often a six or eight-digit figure. The security of TOTP stands out for its use of time as a dynamic factor, generating temporary codes based on synchronized time intervals instead of static values or user-incremented counters.

The generated code is valid only for the brief time window, disappearing as time progresses. This process ensures that successful login requires knowledge of both the shared secret key and synchronized time (to within some degree of margin).

Synchronization and time factors

Synchronization in TOTP systems involves ensuring that both the user’s device and the server maintain a consistent time reference. This consistency is crucial as the TOTP generation algorithm depends on a relatively precise time window. 

Most smartphones and servers use Network Time Protocol (NTP) to automatically adjust and sync time data, reducing the margin for error. A minor time skew might require a brief leeway or tolerance window, allowing the server to accept codes generated shortly before or after the standard period.

Time factors are important in ensuring the reliability and usability of TOTP. Significant discrepancies in time settings between client devices and authentication servers can lead to failed login attempts, making accurate timekeeping essential. Developers must implement careful checks and potentially offer feedback mechanisms for users facing time-related issues.

Tips from the expert

anthony Dombrowski

Anthony Dombrowski Developer Relations

Anthony Dombrowski is a product manager and developer advocate with expertise in developer experience, cybersecurity, and product strategy. He has led initiatives at Ping Identity and DevNetwork to enhance developer tools, authentication processes, and user experiences.

Anthony Dombrowski is a product manager and developer advocate with expertise in developer experience, cybersecurity, and product strategy. He has led initiatives at Ping Identity and DevNetwork to enhance developer tools, authentication processes, and user experiences.

  • Adopt phishing-resistant second-factor options alongside TOTPs: TOTPs alone can be vulnerable to real-time phishing attacks. Complement them with methods like FIDO2/WebAuthn-based authentication to ensure phishing-resistant second factors for high-security applications.
  • Secure secret sharing during enrollment: During TOTP setup, ensure the secret key (seed) is delivered to the client securely.
  • Implement device binding: Bind TOTPs to a specific device through unique identifiers and secure storage (e.g., a secure enclave) to mitigate risks of TOTP keys being extracted or transferred to unauthorized devices.
  • Use adaptive authentication with TOTPs: Step-up from TOTP authentication with risk-aware steps. For example, flag and prompt for additional verification if a TOTP login occurs from an unusual location, device, or time.
  • Protect TOTP seeds with encryption and HSMs: Store server-side TOTP seeds (the shared secret) using encryption and in hardware security modules (HSMs). Ensure secrets are accessible only to authentication processes and not to general application layers.

Security benefits of TOTPs 

TOTPs offer several critical security advantages, making them a popular choice for improving authentication processes:

  • Resistance to phishing attacks: Unlike static passwords, TOTPs are valid only for a short period. This time constraint limits an attacker’s ability to misuse a captured code, even if they successfully trick a user into sharing it.
  • Mitigation of replay attacks: Since TOTPs are dynamically generated for specific time intervals, they cannot be reused once that time period has expired. This feature significantly reduces the risk of replay attacks, where an intercepted credential is reused by attackers to gain unauthorized access.
  • Can continue to function while offline: TOTP generation does not require a continuous network connection, as codes are calculated locally using a secret key and the current time. This lowered requirement improves security by reducing exposure to network-based attacks.
  • Protection against credential stuffing: Credential stuffing attacks exploit reused usernames and passwords across multiple services. Since TOTPs rely on a unique shared secret for each account, even if a password is compromised, unauthorized access is prevented without the associated TOTP.
  • Limited attack window: The time-based nature of TOTPs creates a narrow window for attackers to exploit stolen codes. Additionally, many implementations allow for detection of repeated or failed attempts within a short timeframe, enabling real-time defenses like account lockouts or alerts.
  • No hardware dependency: With the widespread availability of TOTP apps, users no longer require specialized hardware tokens. This shift reduces costs and logistical challenges while maintaining high security standards. Apps like Google Authenticator and Authy store secrets securely.

Security risks inherent in TOTPs 

While time-based one-time passwords provide strong 2FA capabilities, they are not without vulnerabilities. The reliance on shared secrets, time synchronization, and implementation choices introduces potential risks, which malicious actors can exploit under certain conditions.

Vulnerability to brute force attacks

TOTPs are usually limited to a small range of possible values, typically six or eight digits, making brute-force attacks feasible without rate-limiting measures. For example, in the CVE-2023-43320 case, an attacker exploited a lack of rate limiting in Proxmox’s TOTP implementation, allowing multiple authentication attempts with different codes. 

By automating requests at high speeds (e.g., 10 attempts per second), attackers demonstrated that valid tokens could be discovered within hours, compromising the system’s security.

Risks from shared secrets

The TOTP algorithm depends on a secret key shared between the client and server. If an attacker gains access to the secret—whether through a database breach, client compromise, or insecure distribution—they can generate valid TOTPs indefinitely. 

Unlike passwords, where a compromised secret can be reset, the shared nature of TOTP keys requires secure management and protection at multiple points, increasing the attack surface.

Real-time phishing attacks

Although TOTPs are resistant to static credential theft, attackers can intercept valid tokens via real-time phishing or man-in-the-middle attacks. In such cases, they relay the token immediately to gain access before it expires. 

This weakness underscores the importance of combining TOTPs with other phishing-resistant authentication methods, such as hardware-based security keys.

Challenges with time synchronization

TOTPs rely on precise time synchronization between the server and client. While small discrepancies can be addressed through tolerance windows, larger time offsets lead to failed authentications or acceptance of incorrect tokens. 

Attackers might exploit this by deliberately desynchronizing clocks or targeting systems that handle time synchronization poorly, potentially bypassing security measures.

Rate limiting and implementation weaknesses

The effectiveness of TOTPs heavily depends on proper implementation. Without mechanisms like rate limiting, logging failed attempts, or locking accounts after multiple incorrect codes, attackers can exploit weaknesses to launch targeted attacks. 

Additionally, poorly implemented error handling might inadvertently expose information about valid tokens or authentication status.

Related content: Read our guide to passwordless authentication

Best practices for using TOTPs 

Organizations should adopt the following practices to ensure the most secure use of time-based one-time passwords.

Use strong seed values

Implementing strong seed values is critical for TOTP security, serving as the foundational element from which time-based codes are generated. These seeds must be cryptographically secure, utilizing high-entropy randomness to ensure unpredictability. Weak or predictable seeds can compromise authentication integrity, allowing attackers to precompute potential codes. 

Rigorous random number generation methods enable the creation of strong seeds. To prevent exposure during initialization or other interactions, seed values should be encrypted and stored securely. Utilizing HSMs for seed generation and storage can add an extra layer of protection. 

Implement time skew allowance

Incorporating a time skew allowance is essential when using TOTPs, as it provides tolerance for slight time discrepancies between user devices and servers. A balanced skew window, typically one or two intervals beyond the standard TOTP period, can accommodate inevitable minor sync differences without compromising security. This ensures that authentication attempts remain valid.

Proper configuration of time skew settings involves careful consideration of security and usability trade-offs. Overly generous skew allowances may weaken security, while stringent settings could cause unnecessary failures. Monitoring authentication attempts for pattern analysis can help fine-tune these settings. 

Educate users on phishing risks

User education is crucial in raising awareness about phishing risks that seek to undermine authentication processes. Attackers often attempt to deceive users into revealing genuine codes. Training users to recognize phishing attempts, such as verifying source legitimacy before entering codes and understanding secure communications, is vital to protecting system integrity.

Continuous user engagement, through educational materials and simulated phishing tests, improves vigilance. Encouraging security-conscious behavior extends beyond TOTP use. By embedding awareness into user interaction frameworks, organizations substantially minimize vulnerability to phishing attacks and other social engineering threats.

Regularly update and monitor security

Regular updates and vigilant monitoring are foundational to maintaining TOTP security. Ensuring software components, including TOTP generators and associated infrastructure, remain up to date against vulnerabilities is critical. Regular updates address potential exploits and adapt authentication mechanisms to current threat landscapes. 

This proactive approach encompasses both application and server-side updates. Monitoring authentication systems for irregularities helps detect potential security incidents early. Automated systems to track failed attempts, usage spikes, and anomalies in authentication patterns can inform rapid response measures. 

Combine TOTPs with other security measures

Combining TOTPs with additional security layers fortifies authentication systems by integrating multi-factor approaches. Techniques such as biometric authentication, security questions, or hardware tokens can complement the time-based aspect of TOTPs. Layering these methodologies creates a multi-faceted defense strategy.

The approach to multi-layered security must ensure that each component functions smoothly. Evaluations of the system’s collective strength and potential areas for intrusion inform necessary adjustments. 

Implementing TOTP securely with Frontegg

Frontegg makes it simple to roll out TOTPs as part of your authentication flow, without overloading your development team. With built-in MFA support, secure key handling, and low-code configuration, Frontegg gives your organization the ability to enforce strong identity controls while reducing implementation effort. 

Admins can enable and manage TOTP directly through the Frontegg portal, putting control in the hands of teams who need it, without waiting on engineering. Start securing access the smarter way.

Sign up for free and try Frontegg today.