TOTP, short for time-based one-time password, is usually a six-digit code that an authenticator app and a server each calculate from a shared secret and the current time. The code changes every 30 seconds by default. A sign-in succeeds when the code the person types matches the one the server calculated. RFC 6238 defines it.

This guide is for developers, and for anyone choosing a second factor for a product or a team. It covers how a code is calculated and enrolled, how secure TOTP is, how it compares with SMS, push and passkeys, and how to implement it: secret storage, one-time use, guess limits, recovery and step-up authentication. Standards and products are described as of December 2026. The product examples come from platforms we build and run.

What is TOTP and how does it work?

TOTP is the time-based form of the HMAC-based one-time password (HOTP) algorithm. RFC 4226, from December 2005, defines HOTP, and RFC 6238, from May 2011, replaces HOTP's counter with a value taken from the clock. Both are Informational RFCs rather than Internet Standards, yet MDN notes that a large number of authenticator apps support TOTP.

It usually serves as the second factor in two-factor authentication (2FA), a form of multi-factor authentication (MFA): the password is something the person knows, and the phone holding the secret is something they have.

The person and the server share one secret key, the seed, set up once at enrolment. After that neither needs to contact the other. Each divides the current Unix time, in seconds, by the time step and rounds down. The result, T, counts whole steps since 1 January 1970. The default step is 30 seconds, so T is 1 at 59 seconds and 2 at 60 seconds. The app needs only a clock, so it works without a signal: Google says its Authenticator app makes codes without an internet connection or mobile service.

A phone and a server each show a row of six code squares and a small clock. One orange key above them is linked by dashed lines to both, and a dotted line with a check mark joins the two codes.
Fig. 1 Phone and server each work out the code alone, from the same secret and the same clock reading.

TOTP is HOTP computed over T. The table follows one calculation with the RFCs' test values: the secret is the ASCII string 12345678901234567890 and the time is 59 seconds.

StepWhat happensWorked example
1. Count stepsDivide the Unix time by 30 and round down59 seconds gives T = 1
2. HashHMAC-SHA-1 of T as eight bytes, keyed with the secret75a48a19d4cbe100644e8ac1397eea747a2d33ab
3. Pick four bytesThe low four bits of the last byte give an offset; read four bytes there, clear the top bitLast byte 0xab gives offset 11; c1397eea becomes 41397eea, which is 1,094,287,082
4. ShortenKeep the remainder after dividing by 10 to the power of the digit countSix digits: 287082. Eight digits: 94287082

How is TOTP different from HOTP?

HOTP counts uses and TOTP counts time, so an HOTP code stays valid until the server's counter moves past it, while a TOTP code expires by itself. The counter is HOTP's weak spot. A token raises it whenever the user asks for a code, even if the code is never submitted, so it can run ahead of the server. RFC 4226 has the server check a look-ahead window to catch up. TOTP swaps that problem for another: the two clocks must agree.

HOTP (RFC 4226)TOTP (RFC 6238)
Moving factorA counter that rises by one per codeThe Unix time divided by the time step
A code lastsUntil the server's counter passes itAbout one time step, plus any delay you allow

For a web sign-in, implement TOTP: Microsoft Entra ID, for one, supports OATH TOTP and does not support HOTP.

How does enrolment work, and what is an otpauth URI?

At enrolment the server creates the secret and shows it as a QR code, which the person scans with an authenticator app. The QR code holds an otpauth URI, a format that Google documented for its Authenticator app in a wiki page of a repository archived since April 2021.

A server sends data to a laptop whose screen shows a square grid like a QR code in orange. A phone held toward the screen looks at the grid along a dashed cone and shows a small padlock.
Fig. 2 The secret reaches the phone once, through the screen, and the server never has to show it again.

The page's own example shows the shape:

otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example

The label names the account, with the issuer in front as the wiki recommends, the secret is Base32 without padding, and the issuer parameter names the service. Three optional parameters, algorithm, digits and period, also exist, but Google's page says its apps ignore the algorithm and the period, and the digits on Android. A draft that would standardize the format, revision 03 of 24 August 2026, says some authenticators still ignore all three. It is an individual Internet-Draft with no formal standing in the IETF, so read it as work in progress.

So stay with the defaults that apps fall back on: SHA-1, six digits and a 30-second period. SHA-1 inside HMAC is not the red flag it is elsewhere. RFC 4226's appendix concluded in 2005 that the new attacks on SHA-1 had no impact on HMAC-SHA-1, and RFC 6238 rests on that analysis.

Apps differ in what happens to the secret afterwards, which matters for recovery. Google Authenticator can sync codes to a Google Account or keep them on one device. Microsoft Authenticator can back up one-time password codes, restoring them only on the same type of device. Apple's Passwords app stores verification codes from iOS 18. Assume a seed can live on more than one device.

How long is a TOTP code valid, and what about clock drift?

The server works out the code for the current step and the previous one and accepts either, because a code read at the end of one step often arrives in the next. RFC 6238 recommends allowing at most one step for network delay, and the OWASP Multifactor Authentication Cheat Sheet gives the same baseline. The clock must be the server's own, never one the client supplies: the OWASP ASVS asks for a time source from a trusted service (requirement 6.5.8 in version 5.0.0).

Six equal blocks in a band, a clock marker in the fifth. An orange bracket covers the fourth and fifth; two code cards feed into it, and a third, above the second block, is stopped by a short bar.
Fig. 3 A code is accepted for the current step and the one before it, then it is too old.

Every extra step widens the window: a leaked or relayed code stays usable for longer, and the guess odds rise. A six-digit code has 1,000,000 values, so each accepted step adds one chance in a million to every guess. RFC 4226 puts an attacker's success at s × v ÷ 10^Digit, with s the number of values accepted and v the number of attempts. The table applies that to the 100 consecutive failures that NIST's SP 800-63B-4, final since July 2025, sets as its upper limit.

Server acceptsA code works forChance per guessAfter 100 guesses
The current step onlyup to 30 seconds1 in 1,000,000about 0.01%
Current and previous stepup to 60 seconds2 in 1,000,000about 0.02%
Previous, current and nextup to 60 seconds; 90 with a fast phone clock3 in 1,000,000about 0.03%

OWASP's ASVS 5.0.0 is stricter: requirement 6.5.5, from level 2 up, caps a TOTP's lifetime at 30 seconds. With a 30-second step only the first row meets it, and a code typed late in its step is refused. NIST leans the other way: the lifetime should allow for clock drift, network delay and typing. Pick one and record why.

Clock drift is the other problem: a phone whose clock is off by more than a step never matches. RFC 6238 describes recording each token's detected drift in whole steps, and OWASP advises doing that instead of widening the window for everyone. Google Authenticator 7.0 dropped its time-correction setting and uses the operating system's time. For those users the fix is the phone's own clock settings, and Google's help tells people with a rejected code to check that the phone's time is synced.

Tip

Tell people why a code failed. Google's own list is an expired code, the wrong app or account, and a phone clock that is not synced. Do not widen the window for everyone to fix one phone.

How secure is TOTP?

What it stops

A password that was guessed, reused or leaked is all an attacker needs when it is the only factor, and a second factor the attacker lacks breaks that path. A 2023 Microsoft study posted to arXiv found that MFA cut the risk of compromise by 99.22%, and by 98.56% where the password had leaked. In that leaked-password sample, MFA failed in 0.99% of attacks against accounts using authenticator-app codes and 1.66% against SMS.

What it does not stop

A person types a TOTP code, and NIST's SP 800-63B-4 draws the consequence. An authenticator whose output is entered by hand is not phishing-resistant, because entering it does not bind it to the session being authenticated. An impostor can relay it to the real verifier. In adversary-in-the-middle (AiTM) phishing, a look-alike site proxies the real sign-in page, collects the password and code as they are typed, passes them on in real time and keeps the session that comes back. OWASP names the reverse-proxy kits: Evilginx, Modlishka and Muraena.

A laptop sends a sign-in to an orange look-alike window, which passes a code envelope on to a server. A round token returns to the look-alike window and goes on by a dashed arrow to a second laptop.
Fig. 4 The look-alike site passes the code to the real one in time, so a correct, unused code still lets the attacker in.

In July 2022, Microsoft reported an AiTM campaign that had targeted more than 10,000 organizations since September 2021, and stressed that the attacker takes over a session the user authenticated, so it is no flaw in MFA itself. Canada's Cyber Centre counted more than 100 such campaigns against Microsoft Entra ID accounts between 2023 and early 2025, and says phishing-resistant MFA is the only way to stop them completely.

Warning

Refusing a code that was already used does not stop a relay. OWASP says so directly: the rule stops a code captured after use from being replayed, but not a proxy that relays the code before the person submits it.

Other weak points

  • The secret. The server keeps it recoverable, so anyone who obtains it can generate valid codes until the person enrols again; OWASP notes that changing the password does not invalidate it.
  • The phone. It can be compromised or lost, and seeds may sit in cloud backups.
  • The reset path. An attacker who cannot beat the code can ask for the factor to be moved. CISA's advisory AA23-320A, revised July 29, 2025, describes calls that persuade an IT help desk to reset passwords or transfer MFA tokens, after which the attackers register tokens of their own.

The verdict

TOTP is a good, widely supported second factor, and it is not phishing-resistant authentication. NIST still lets a password plus a single-factor OTP meet its second authenticator assurance level (AAL2), but requires verifiers to offer at least one phishing-resistant option there. CISA's 2022 fact sheet ranks app-based codes and number-matched push among the best options for small and medium-size organizations that cannot yet deploy phishing-resistant MFA.

TOTP vs SMS, push and passkeys: which should you offer?

"TOTP vs SMS" compares delivery more than algorithm. An SMS code is a one-time password too, but the server creates it and sends it over the phone network, while a TOTP code is computed on the phone and nothing is sent. MDN's advice gives the order: prefer TOTP to SMS, avoid SMS especially, and use passkeys for general authentication, with TOTP as an extra factor or to confirm an intent such as a payment.

MethodPhishing-resistant?Main weaknessWhat NIST and CISA say
TOTP appNoSeed theft, real-time relay, a lost phoneNIST: allowed with a password at AAL2. CISA: among the best options short of phishing-resistant MFA
SMS or voiceNoSS7 interception, SIM swap, number portingNIST: its one restricted authenticator. CISA: last resort
Push with number matchingNoPhishing; push bombing without number matchingCISA: same tier as app codes
Passkey or security keyYesUneven support; rollout needs training and supportNIST: phishing-resistant by verifier name binding. CISA: the gold standard

Passkeys and security keys use WebAuthn, which the W3C published as a Level 3 Recommendation on 25 August 2026. A credential is created for one relying party and can only be used by that party's origins, so a look-alike domain cannot ask for it. Google's 2019 study shows the ranking in numbers. An SMS code to a recovery phone blocked 96% of bulk phishing attacks and 76% of targeted ones, and on-device prompts blocked 99% and 90%. No user who relied only on security keys fell to targeted phishing in the study.

CISA's mobile guidance for highly targeted individuals (version 2.0, November 2025) says not to use SMS as a second factor, and warns that enrolling an app does not remove SMS, which can linger as a weak fallback.

What to offer depends on who signs in:

  • Customers and members: passkeys where they work, TOTP as the fallback almost any smartphone can run, and no accounts that depend on SMS alone. For personal accounts, our guide to staying safe online covers passkeys and a password manager.
  • Staff and administrators: a phishing-resistant method, with weaker backups removed, as the Cyber Centre advises for administrators because an AiTM campaign could use them. Our small business checklist gives the order.
  • Only SMS possible: NIST allows it with an unrestricted alternative, a risk warning and a migration plan; OWASP says not to use it where personal information or financial risk is involved.

How do you implement TOTP properly?

MDN advises using a reputable library to generate secrets and codes. The policy around the library is still yours to get right, and the steps below are in build order.

1. Generate the secret and keep it encrypted

Generate at least 128 bits and preferably 160 from the operating system's cryptographically secure random generator. RFC 4226 requires the first and recommends the second, and ASVS 6.5.3 asks for a secure generator for TOTP seeds. Encode the result in Base32 for the URI.

You cannot hash the secret as you would a password, because the server must recompute codes from it. OWASP says to store it encrypted, ideally under a key held in a hardware security module or a key management service, to decrypt it only while verifying a code, and never to return it to the client after enrolment. Bind each ciphertext to its account with authenticated encryption, so a row copied to another account does not decrypt, and keep the secret out of logs. If a database leak may have exposed the secrets, make every affected person enrol again.

A database cylinder with a padlock on the left and a separate key box holding an orange key on the right. Arrows from both meet at a gear on a server in the middle, and no line joins the database to the key box.
Fig. 5 The database holds only ciphertext; the key that opens it sits somewhere else.

Our own site's admin works this way: every admin must use a code, and each seed is sealed with a key held outside the database and tied to its account. If the key is lost, every admin sets up again, which is the right way to fail.

Good Cleaner Co., a local cleaning company serving Ottawa homes and businesses whose site we build and run, takes the same stance for its admin console. The server creates the secret and holds it encrypted. The browser receives only the authenticator link, and finishing enrolment takes a one-time challenge plus a code from the app, so nothing the browser sends can choose or replace the factor. If a deployment has no encryption key, enrolment stays off rather than storing secrets as plain text.

2. Confirm enrolment before you rely on it

Keep the new secret as pending until the person submits one valid code from the app. That proves the scan worked and the clock is right, and it stops you locking someone out with a factor they never set up. Only then mark the factor active, show the recovery codes and start requiring a code at sign-in. Let pending secrets expire.

3. Verify a code, once

The sample is Node.js and uses only node:crypto. It follows RFC 4226 and RFC 6238 and passes their published SHA-1 test vectors. Use a maintained library in production; this shows where the policy goes. It accepts the current and previous step; for ASVS 6.5.5, loop over the current step only.

import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";

const STEP_SECONDS = 30; // RFC 6238 default
const DIGITS = 6;

/** 160 random bits from the operating system's CSPRNG. */
export const newSecret = (): Buffer => randomBytes(20);

/** RFC 4226: HMAC-SHA-1 over an 8-byte big-endian counter, then truncation. */
export function hotp(secret: Buffer, counter: number, digits = DIGITS): string {
  const message = Buffer.alloc(8);
  message.writeBigUInt64BE(BigInt(counter));
  const mac = createHmac("sha1", secret).update(message).digest(); // 20 bytes
  const offset = mac[19]! & 0x0f; // low 4 bits of the last byte
  const binary = mac.readUInt32BE(offset) & 0x7fffffff; // 4 bytes, top bit cleared
  return String(binary % 10 ** digits).padStart(digits, "0");
}

export const stepAt = (nowMs: number): number =>
  Math.floor(nowMs / 1000 / STEP_SECONDS);

/** The time step a code belongs to, or null. A step at or before `lastStep`
 * (the newest already accepted for this user) is refused, so a code works once. */
export function matchTotp(
  secret: Buffer,
  code: string,
  lastStep: number,
  nowMs = Date.now(),
): number | null {
  if (!/^\d{6}$/.test(code)) return null;
  const supplied = Buffer.from(code);
  const now = stepAt(nowMs);
  let matched: number | null = null;
  for (const step of [now - 1, now]) {
    // Compare both in constant time; do not return early.
    const equal = timingSafeEqual(supplied, Buffer.from(hotp(secret, step)));
    if (equal && step > lastStep) matched = step;
  }
  return matched;
}

The caller must save the step matchTotp returns. Saving is where reuse is prevented, and it must be atomic, or two parallel requests can both spend one code:

UPDATE totp_credentials
   SET last_step = $1
 WHERE user_id = $2 AND last_step < $1;

Accept the sign-in only if exactly one row changed. Set last_step when enrolment is confirmed, because a NULL never matches this update. RFC 6238 says a verifier must not accept a second attempt of a code after a successful validation. OWASP says to store the last accepted step per token and update it atomically, so parallel verifier instances cannot both accept the same code. Node's timingSafeEqual throws on inputs of different lengths, so the sample checks the format first.

Test against the standards' vectors, RFC 4226 Appendix D and RFC 6238 Appendix B. One trap: RFC 6238's text names a single test secret, but its errata say the SHA-256 and SHA-512 vectors use secrets of 32 and 64 bytes.

Good Cleaner Co. applies the same rule to its admins. It keeps the newest accepted time step for each credential, takes a row lock and decrypts the secret only for the check. It accepts a code only if the update that advances the step changes a row. Its sign-in, counter and audit record share one reading of the database clock. Its recovery codes work the same way: shown once, stored only as digests, and spent by one conditional update that matches only an unused code.

4. Limit guesses

A six-digit code needs limits, because a guesser gets a million-to-one chance per try. NIST requires verifiers to limit consecutive failed attempts per authenticator to no more than 100 by disabling it, and says it chose 100 to balance the chance of a correct guess against the need for recovery. For authenticator output under 64 bits it requires a rate-limiting mechanism. RFC 4226 adds that delays or lockouts must hold across login sessions, so parallel guessing is counted together. Count failures per account, not per session or per address, and tell the person how long to wait. Our rate limiting guide covers what to count, how sign-in and one-time code limits should work, and what to do when the counter store is down.

5. Cover every route that can start a session

Second factors fail at the edges. OWASP's list of where to require MFA ends with a warning: when an application offers several ways to authenticate, all of them should require MFA or have other protections, and a common miss is a separate login API or a mobile app. ASVS 6.3.4 asks the same of any application with multiple authentication pathways, and ASVS 6.4.3 says password reset must not bypass an enabled second factor.

Minute Notary, an online notary platform we build and run, ran into this with its authentication library. The library's two-factor check covered the password sign-in endpoints, so we gated the other ways to end up with a session ourselves. A session issued on one of those routes is revoked and the person is sent to the same code challenge until the code is entered, and an integration test puts a real code through the real stack. Earlier, in July 2026, an upgrade of the library had added lock-out bookkeeping that our database lacked, and every correct code failed at the last step until we added it.

6. Ask again before sensitive actions

A code at sign-in proves who started the session. For actions that cannot be undone or that move money, ask again, with a fresh code, checked on the server: a prompt that only the browser enforces guards honest users alone. OWASP's candidates, beyond sign-in, are changing the password or security questions, changing the email address, disabling MFA and elevating a session to an administrative one.

A laptop sends an envelope through an open gate toward a trash can, but an orange gate in front of the can stays shut. A dashed arrow brings a code card from a phone up to that gate.
Fig. 6 A second gate that only a fresh code opens stands in front of the actions that cannot be undone.

Where an identity provider handles sign-in, RFC 9470 (September 2023) defines the handshake. The resource server answers insufficient_user_authentication and names the authentication context (acr_values) or maximum age (max_age) it needs, and the client sends the person back to the authorization server. ASVS 6.8.4 adds that the application should check what the provider reports, such as the acr, amr and auth_time claims.

Minute Notary asks for a fresh authenticator code before a short list of admin actions that are hard to take back, such as permanently deleting a booking, erasing a customer's data and creating an offline payment link. The check runs on the server, which decrypts the stored secret and verifies the code, so a client that skips the prompt cannot complete the action. Deleting a booking also makes the admin retype its reference, the last guard against acting on a stale tab. Routine edits do not ask. Good Cleaner Co. chose differently. It first asked for a code for each admin action, until an operator updating five lead statuses had typed five codes and none to enter the console. It moved the check to sign-in. Both answer one trade-off, so draw the line on purpose, by what an action can do that you cannot take back.

How should recovery codes and lost phones be handled?

Phones are lost, wiped and replaced, so enrolment needs a way back. OWASP's list of recovery methods starts with single-use recovery codes handed over at set-up, and goes on to a code mailed to the registered address, a rigorous support process and vouching by another trusted user. NIST adds the details for saved recovery codes: at least 64 random bits each, stored hashed, invalidated after use, throttled like other guesses, with a notification when a replacement is issued or a recovery happens.

A printed sheet with eight short bars, three crossed out. One uncrossed bar is orange and sends an arrow through an open gate to a laptop whose screen shows an open padlock.
Fig. 7 Each recovery code works once; a spent code is crossed off for good.

In practice:

  1. Generate the codes with the same secure random generator when the person confirms enrolment, with at least 112 bits each. ASVS allows an ordinary hash for secrets with that much entropy and asks for a salted password-hashing function for shorter ones.
  2. Show them once and store only a digest of each.
  3. Spend a code with one conditional update inside a transaction, so two requests cannot spend the same one.
  4. Notify the person, outside the sign-in page, when a code is used, codes are regenerated or a factor changes.
  5. Require a current code, or a recovery code, before regenerating codes or replacing a factor; OWASP says not to rely on the session alone.

The help desk is part of the attack surface. ASVS 6.4.4 asks for identity proofing at the same level as at enrolment when a factor is lost, and the calls in the AA23-320A advisory show why. Write the support procedure as carefully as the code: verify the person, tell the account's owner, and for admins add a delay or a second approver. OWASP suggests delays for high-value accounts. NIST also says to encourage at least two separate means of authentication, and, on a new phone, to bind the new app and invalidate the old one.

What should you test, and where can we help?

Test the second factor the way an attacker would, by trying to get past it:

  1. Run the standards' test vectors through your code.
  2. Submit one valid code twice, including at the same moment from two requests. Exactly one may succeed.
  3. Try a code from two steps ago and one from the next step. Both must fail if your window is the current and previous step.
  4. Guess wrong codes past the limit from several sessions at once. The account's counter must stop them all, and a counter you cannot read must refuse, not allow.
  5. Sign in by every route you offer: password, identity provider, email link, API and mobile app. Each must end in the code challenge.
  6. Spend a recovery code twice, and reset a password with the factor enabled. The second spend must fail, and the reset must still ask for the factor.
  7. Repeat the sign-in test with a real code after every upgrade of the authentication library.

A penetration test covers what a scanner cannot, such as the reset path and the routes in item 5. Our security testing service tests web apps and APIs signed in at every role, including sign-in, sessions and password reset. Our custom software development work takes its sign-in and session requirements from OWASP ASVS 5.0, chosen per project. To roll a second factor out to a team, see IT support, which covers MFA, conditional access and phishing-resistant sign-in where possible. The wider habits are in our secure coding checklist.