Definition

What Is TOTP? Time-Based One-Time Passwords Explained

The six-digit code in your authenticator app isn't random. Here's how TOTP turns a shared secret and the clock into a code, why it beats SMS, and how to verify one safely.

TOTP vs SMS one-time passwords

TOTP (authenticator app)

SMS OTP

Where the code comes from

Computed on the user's device

Generated by the server and sent by text

Needs signal to receive

No; works offline

Yes

Cost per login

None

A per-message SMS fee

SIM swap and number porting

Not affected

An attacker who takes the number gets the codes

Phishing resistance

No; a fake site can relay the code

No; same relay risk

Setup

Scan a QR code once

Enter and confirm a phone number

Lost phone

Use backup codes or a recovery process

A new SIM on the same number restores access

NIST SP 800-63B

Accepted OTP authenticator

Restricted authenticator

What is TOTP?

TOTP is the code in your authenticator app. Google Authenticator, Microsoft Authenticator and many password managers generate TOTP codes. It's a popular second factor because it works offline, costs nothing per login and doesn't need a phone number.

The IETF published the standard as RFC 6238 in 2011. It builds on HOTP (RFC 4226), an earlier algorithm that uses a counter, by using the current time as the counter instead.

How TOTP works

1. Enrollment

The server generates a random secret. RFC 4226 requires at least 128 bits and recommends 160. The server shows it as a QR code holding an otpauth://totp/... URI with the secret in Base32, the issuer and the account name. The user scans it, and the app stores the secret.

2. Generating a code

Both sides compute a time step: T = floor(current Unix time / 30). The 30-second step is the RFC 6238 default. They run HMAC-SHA-1 over T with the secret, apply HOTP's dynamic truncation and keep the last six digits. RFC 6238 also allows HMAC-SHA-256 and HMAC-SHA-512.

3. Verifying

The user types the code. The server computes the expected code for the current step, and usually one step either side to allow for clock drift and typing time. RFC 6238 recommends allowing at most one step of network delay, and says a code must not be accepted a second time after it has been used.

HOTP vs TOTP vs SMS codes

HOTP uses a counter that goes up by one each time a code is generated. TOTP uses the clock. That one change matters:

  • HOTP codes stay valid until they're used, so an intercepted code can work later. TOTP codes expire with their time step.

  • HOTP counters fall out of sync when someone generates codes without logging in, so servers search ahead. TOTP only drifts when a clock is wrong.

  • HOTP suits devices without a reliable clock, such as some hardware tokens. Phones always know the time, so apps use TOTP.

SMS codes are generated by the server and texted to the user. They're easy to set up, but they cost money per message, fail without signal, and can be stolen through SIM swaps or number porting. NIST SP 800-63B classes the phone network as a restricted authenticator, so services that use it must offer an alternative and explain the risk. TOTP avoids the phone network entirely.

TOTP verification in Node.js

This example uses the open-source otpauth library. It enrolls a user, then verifies a code with a one-step window and rejects a code that was already used.

import * as OTPAuth from 'otpauth';

// Enrollment: 160-bit secret, store it encrypted, show the URI as a QR code
const secret = new OTPAuth.Secret({ size: 20 });
const enroll = new OTPAuth.TOTP({
  issuer: 'ExampleApp', label: 'alice@example.com',
  algorithm: 'SHA1', digits: 6, period: 30, secret,
});
user.totpSecret = secret.base32;    // encrypt at rest
const uri = enroll.toString();      // otpauth://totp/ExampleApp:alice...

// Login: check the code the user typed
function verifyTotp(user, code) {
  const totp = new OTPAuth.TOTP({ secret: OTPAuth.Secret.fromBase32(user.totpSecret) });
  const timestamp = Date.now();
  const delta = totp.validate({
    token: code, timestamp, window: 1,
    afterCounter: user.lastTotpCounter, // null until first use; blocks replay
  });
  if (delta === null) return false;   // wrong, expired or reused
  user.lastTotpCounter = totp.counter({ timestamp }) + delta; // persist it
  return true;
}

Check delta !== null, never truthiness: a valid code in the current step returns 0.

Rule of thumb: a window of one step, no code accepted twice, rate-limited attempts and an encrypted secret. Skip any one and TOTP gets much weaker.

Where TOTP is used

  • Two-factor login for SaaS dashboards, admin consoles, developer tools and banking.

  • Step-up checks before sensitive actions, such as changing a payout account, exporting data or adding an admin.

  • Chat and community apps. Moderator, admin and support agent accounts can read private conversations and ban users, so they're worth a second factor. End users benefit too where account takeover means someone impersonating them in DMs or group calls.

  • A backup factor alongside passkeys, for devices that don't support them.

Limits and pitfalls

  • TOTP is phishable. A fake login page can ask for the code and replay it within seconds. For phishing resistance, use passkeys or other WebAuthn authenticators.

  • The server holds the secret. Unlike a password hash, the TOTP secret must be stored in a usable form. Encrypt it at rest, because anyone with the secret can generate valid codes.

  • Six digits can be guessed. That's a million combinations, and a three-step window triples the odds per guess. Rate-limit attempts and lock out after repeated failures.

  • Clock drift. A phone with the wrong time produces wrong codes. Keep the window small and sync server time with NTP.

  • Lost devices. Issue one-time backup codes at enrollment, and make sure account recovery isn't easier to abuse than the second factor it replaces.

Securing chat users with TOTP and CometChat

CometChat doesn't replace your login, so your TOTP or other two-factor flow stays where it is. Chat access follows from it.

Your second factor first, then a CometChat auth token

Run your sign-in and TOTP check as usual. Only after both pass does your server request a CometChat auth token for that user with the Create Auth Token endpoint (POST /v3/users/{uid}/auth_tokens), authenticated with your REST API key. Your app passes the token to CometChat.login(authToken), and the SDK manages the session. CometChat auth tokens are not JWTs, and your API key never leaves your server. If an account is compromised, you can delete one or all of that user's auth tokens through the Auth Tokens REST API.

Read the auth docs · Auth tokens API

Frequently asked questions

Is TOTP more secure than SMS?

Yes, in most cases. TOTP codes are computed on the user's device, so SIM swaps and intercepted texts don't expose them, and NIST classes SMS as a restricted authenticator. Both can still be phished, so passkeys are stronger than either.

What is the difference between OTP and TOTP?

OTP (one-time password) is the general term for any code that works once. TOTP is the time-based kind defined in RFC 6238. HOTP is the counter-based kind, and SMS OTPs are codes the server texts to you.

How long is a TOTP code valid?

Each code belongs to a 30-second time step by default. Most servers also accept the code from one step before or after to allow for clock drift, so in practice a code works for up to about 90 seconds unless it has already been used.

Can TOTP be hacked?

The algorithm is sound, but setups can be attacked. Phishing pages can relay codes in real time, a leaked server database can expose secrets, and endpoints without rate limits can be brute-forced. Encrypt secrets, rate-limit attempts and block reused codes.

What happens if I lose my authenticator app?

You use one of the backup codes you saved when you set up two-factor authentication, or go through the service's account recovery process.

Related terms