# TOTP explained: how it works, how secure it is and how to implement it

> TOTP is usually a six-digit code that an app and a server work out from a shared secret and the clock. How it works, how secure it is and how to implement it.

- URL: https://computese.com/totp/
- Author: Kai Mai, Chief Technology Officer, Computese
- Published: 2026-11-02
- Updated: 2026-12-03
- Topics: Security

## In short
- TOTP is usually a six-digit code that an authenticator app and a server each compute from a shared secret and the clock. RFC 6238 defines it on top of HOTP in RFC 4226, and the code changes every 30 seconds by default.
- TOTP blocks nearly all attacks that rely on guessed or leaked passwords and beats SMS, but it is not phishing-resistant: NIST says manually entered codes cannot be, because a look-alike site can relay them in real time. Passkeys and security keys resist that.
- Check a code against the current and previous time step, compare in constant time, and save the newest accepted step atomically so a code works once. Store the secret encrypted under a key held outside the database.
- Limit guesses per account across sessions (NIST caps consecutive failures at 100), cover every route that can start a session, and ask for a fresh code before actions that cannot be undone.
- Issue single-use recovery codes at enrolment and store only their digests. Treat the reset path as an attack target: re-verify the person, notify them of every change, and give admin accounts extra scrutiny.

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](https://www.rfc-editor.org/rfc/rfc6238.html) 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](https://www.rfc-editor.org/rfc/rfc4226.html), 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](https://developer.mozilla.org/en-US/docs/Web/Security/Authentication/OTP) 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](https://support.google.com/accounts/answer/1066447) 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.](https://computese.com/images/blog/totp/shared-secret-clocks.86985b4c39-1536.webp)

*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.

| Step               | What happens                                                                                | Worked example                                                                    |
| ------------------ | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| 1. Count steps     | Divide the Unix time by 30 and round down                                                   | 59 seconds gives T = 1                                                            |
| 2. Hash            | HMAC-SHA-1 of T as eight bytes, keyed with the secret                                       | 75a48a19d4cbe100644e8ac1397eea747a2d33ab                                          |
| 3. Pick four bytes | The low four bits of the last byte give an offset; read four bytes there, clear the top bit | Last byte 0xab gives offset 11; c1397eea becomes 41397eea, which is 1,094,287,082 |
| 4. Shorten         | Keep the remainder after dividing by 10 to the power of the digit count                     | Six 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 factor | A counter that rises by one per code | The Unix time divided by the time step        |
| A code lasts  | Until the server's counter passes it | About 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](https://learn.microsoft.com/en-us/entra/identity/authentication/concept-authentication-oath-tokens).

## 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](https://github.com/google/google-authenticator/wiki/Key-Uri-Format) 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.](https://computese.com/images/blog/totp/enrolment-qr.d440f283fd-1536.webp)

*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:

```text
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](https://datatracker.ietf.org/doc/draft-linuxgemini-otpauth-uri/), 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](https://support.microsoft.com/en-us/account-billing/bb939936-7a8d-4e88-bc43-49bc1a700a40), restoring them only on the same type of device. Apple's [Passwords app](https://support.apple.com/en-us/120758) 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](https://cheatsheetseries.owasp.org/cheatsheets/Multifactor_Authentication_Cheat_Sheet.html) gives the same baseline. The clock must be the server's own, never one the client supplies: the [OWASP ASVS](https://github.com/OWASP/ASVS/blob/v5.0.0/5.0/en/0x15-V6-Authentication.md) 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.](https://computese.com/images/blog/totp/time-step-window.53568bdcdf-1536.webp)

*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](https://csrc.nist.gov/pubs/sp/800/63/b/4/final), final since July 2025, sets as its upper limit.

| Server accepts             | A code works for                             | Chance per guess | After 100 guesses |
| -------------------------- | -------------------------------------------- | ---------------- | ----------------- |
| The current step only      | up to 30 seconds                             | 1 in 1,000,000   | about 0.01%       |
| Current and previous step  | up to 60 seconds                             | 2 in 1,000,000   | about 0.02%       |
| Previous, current and next | up to 60 seconds; 90 with a fast phone clock | 3 in 1,000,000   | about 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](https://arxiv.org/abs/2305.00945) 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](https://pages.nist.gov/800-63-4/sp800-63b.html) 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](https://computese.com/understanding-man-in-the-middle-mitm-attacks/), 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.](https://computese.com/images/blog/totp/relay-phishing.6d5767fbf9-1536.webp)

*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](https://www.microsoft.com/en-us/security/blog/2022/07/12/from-cookie-theft-to-bec-attackers-use-aitm-phishing-sites-as-entry-point-to-further-financial-fraud/) 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](https://www.cyber.gc.ca/sites/default/files/itsm.30.031-e.pdf) 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](https://www.cisa.gov/news-events/cybersecurity-advisories/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](https://www.cisa.gov/sites/default/files/publications/fact-sheet-implementing-phishing-resistant-mfa-508c.pdf) 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.

| Method                    | Phishing-resistant? | Main weakness                                      | What NIST and CISA say                                                                              |
| ------------------------- | ------------------- | -------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| TOTP app                  | No                  | Seed theft, real-time relay, a lost phone          | NIST: allowed with a password at AAL2. CISA: among the best options short of phishing-resistant MFA |
| SMS or voice              | No                  | SS7 interception, SIM swap, number porting         | NIST: its one restricted authenticator. CISA: last resort                                           |
| Push with number matching | No                  | Phishing; push bombing without number matching     | CISA: same tier as app codes                                                                        |
| Passkey or security key   | Yes                 | Uneven support; rollout needs training and support | NIST: 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](https://www.w3.org/TR/webauthn-3/) 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](https://security.googleblog.com/2019/05/new-research-how-effective-is-basic.html) 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](https://www.cisa.gov/resources-tools/resources/mobile-communications-best-practice-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](https://computese.com/cyber-it-security/) 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](https://computese.com/cybersecurity-best-practices/) 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.](https://computese.com/images/blog/totp/sealed-seed.726a85e229-1536.webp)

*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.](https://goodcleaner.ca/), 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`](https://nodejs.org/api/crypto.html). 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.

```ts
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:

```sql
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](https://www.rfc-editor.org/errata/rfc6238) 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](https://computese.com/audit-trail/) 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](https://computese.com/rate-limiting/) 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](https://minutenotary.ca/), 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.](https://computese.com/images/blog/totp/step-up-gate.6f50bde0b7-1536.webp)

*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](https://www.rfc-editor.org/rfc/rfc9470.html) (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.](https://computese.com/images/blog/totp/recovery-sheet.8dfeafc7c9-1536.webp)

*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](https://computese.com/penetration-testing-vs-vulnerability-scanning/) covers what a scanner cannot, such as the reset path and the routes in item 5. Our [security testing](https://computese.com/services/security-testing/) service tests web apps and APIs signed in at every role, including sign-in, sessions and password reset. Our [custom software development](https://computese.com/services/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](https://computese.com/services/it-support/), which covers MFA, conditional access and phishing-resistant sign-in where possible. The wider habits are in our [secure coding checklist](https://computese.com/best-practices-for-secure-coding/).

## Key terms
- **TOTP**: Time-based one-time password: a code worked out with HOTP from a shared secret and the number of time steps since 1 January 1970. RFC 6238 defines it, with a 30-second step by default.
- **HOTP**: HMAC-based one-time password, defined in RFC 4226: an HMAC-SHA-1 of an 8-byte counter, truncated to at least six digits. The counter rises each time a code is generated, so a code stays valid until the server's counter moves past it.
- **Time step**: The length of time one TOTP code covers, 30 seconds by default. The number of whole steps since 1 January 1970 UTC, called T, is the value the HMAC is computed over.
- **Shared secret**: The key, also called the seed, that the authenticator and the server both hold. RFC 4226 requires at least 128 bits and recommends 160. The server must keep it recoverable, so it is stored encrypted, not hashed.
- **otpauth URI**: The address inside an authenticator-setup QR code, in the form otpauth://totp/LABEL?secret=...&issuer=.... Google documented it for its Authenticator app, and an IETF individual draft proposes to standardize it.
- **Phishing-resistant authentication**: Authentication that cannot be relayed to an impostor site, because its output is cryptographically bound to the channel or to the verifier's name. NIST counts WebAuthn, which passkeys and security keys use, as such, and manually entered codes as not.
- **Adversary-in-the-middle (AiTM) phishing**: A phishing attack in which a proxy relays the real sign-in page, captures the password, the one-time code and the session cookie as they pass, and then signs in as the person.
- **Step-up authentication**: Asking for a fresher or stronger proof, such as a new code, before a sensitive action even though the person is already signed in. RFC 9470 defines a handshake for it in OAuth.
- **Recovery code**: A single-use code issued at enrolment that lets a person back in when the authenticator is lost. NIST asks for at least 64 random bits and storage in hashed form.

## Common questions

### What is TOTP?

TOTP, or time-based one-time password, is usually a six-digit code that an authenticator app and a server each compute from a shared secret and the current time, usually changing every 30 seconds. RFC 6238 defines it on top of the counter-based HOTP algorithm in RFC 4226. It most often serves as the second factor in two-factor authentication: you enter your password, then the current code.

### Is TOTP secure, and can it be phished?

TOTP is far safer than a password alone: a 2023 Microsoft study found that MFA cut the risk of compromise by 99.22%. It is not phishing-resistant, because a look-alike site can relay a code you type, in real time, to the real site. NIST says manually entered one-time codes cannot be phishing-resistant, so offer passkeys or security keys for accounts that can move money or change other accounts.

### What is the difference between TOTP and HOTP?

HOTP derives each code from a counter that rises each time a code is generated, and RFC 4226 defines it. TOTP derives it from the time, so a code expires by itself after about one time step, 30 seconds by default, and RFC 6238 defines it. A token's HOTP counter can run ahead of the server, which TOTP avoids at the price of needing two agreeing clocks.

### Is TOTP better than SMS?

In most respects, yes. An SMS code crosses the phone network, where SS7 interception, SIM swaps and number porting can expose it, and NIST treats that delivery as its one restricted authenticator; a TOTP code is computed on the phone and never sent. In the leaked-password sample of a Microsoft study, MFA failed in 0.99% of confirmed attacks for authenticator-app codes and 1.66% for SMS. Neither is phishing-resistant.

### Why is my authenticator code not working?

Check the phone's clock first: it must be synced, and Google Authenticator 7.0 and later uses the operating system's time with no correction setting. Then check that you are using the code for the right app and account, and that you entered it before it expired. If it still fails, use a recovery code and ask the service to reset your authenticator.

### What if I lose the phone with my authenticator app?

Use a recovery code saved when you set up two-factor sign-in, or another device where the app's codes were synced. Google Authenticator can sync codes to a Google Account, and Microsoft Authenticator can back up one-time codes for personal and third-party accounts, though only to the same type of device. With neither, the service has to verify who you are before it resets the factor, which can involve waiting.

## Sources
1. [RFC 6238: TOTP: Time-Based One-Time Password Algorithm](https://www.rfc-editor.org/rfc/rfc6238.html), IETF
2. [RFC 4226: HOTP: An HMAC-Based One-Time Password Algorithm](https://www.rfc-editor.org/rfc/rfc4226.html), IETF
3. [One-time passwords (OTP)](https://developer.mozilla.org/en-US/docs/Web/Security/Authentication/OTP), MDN Web Docs
4. [Get verification codes with Google Authenticator](https://support.google.com/accounts/answer/1066447), Google Account Help
5. [Authentication methods in Microsoft Entra ID: OATH tokens](https://learn.microsoft.com/en-us/entra/identity/authentication/concept-authentication-oath-tokens), Microsoft Learn
6. [Key Uri Format](https://github.com/google/google-authenticator/wiki/Key-Uri-Format), Google Authenticator wiki on GitHub
7. [One-Time Password (OTP) Credential Provisioning URI Format: otpauth (draft-linuxgemini-otpauth-uri-03)](https://datatracker.ietf.org/doc/draft-linuxgemini-otpauth-uri/), IETF
8. [Back up one-time password codes in Microsoft Authenticator](https://support.microsoft.com/en-us/account-billing/bb939936-7a8d-4e88-bc43-49bc1a700a40), Microsoft Support
9. [Use the Passwords app to create, manage, and share passwords and passkeys across Apple devices](https://support.apple.com/en-us/120758), Apple Support
10. [Multifactor Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Multifactor_Authentication_Cheat_Sheet.html), OWASP Cheat Sheet Series
11. [Application Security Verification Standard 5.0.0: V6 Authentication](https://github.com/OWASP/ASVS/blob/v5.0.0/5.0/en/0x15-V6-Authentication.md), OWASP
12. [SP 800-63B-4, Digital Identity Guidelines: Authentication and Authenticator Management](https://csrc.nist.gov/pubs/sp/800/63/b/4/final), NIST
13. [How effective is multifactor authentication at deterring cyberattacks?](https://arxiv.org/abs/2305.00945), arXiv
14. [NIST SP 800-63B-4: full text](https://pages.nist.gov/800-63-4/sp800-63b.html), NIST
15. [From cookie theft to BEC: Attackers use AiTM phishing sites as entry point to further financial fraud](https://www.microsoft.com/en-us/security/blog/2022/07/12/from-cookie-theft-to-bec-attackers-use-aitm-phishing-sites-as-entry-point-to-further-financial-fraud/), Microsoft Security Blog
16. [Defending against adversary-in-the-middle threats with phishing-resistant multi-factor authentication (ITSM.30.031)](https://www.cyber.gc.ca/sites/default/files/itsm.30.031-e.pdf), Canadian Centre for Cyber Security
17. [Scattered Spider (AA23-320A)](https://www.cisa.gov/news-events/cybersecurity-advisories/aa23-320a), CISA
18. [Implementing Phishing-Resistant MFA](https://www.cisa.gov/sites/default/files/publications/fact-sheet-implementing-phishing-resistant-mfa-508c.pdf), CISA
19. [Web Authentication: An API for accessing Public Key Credentials, Level 3](https://www.w3.org/TR/webauthn-3/), W3C
20. [New research: How effective is basic account hygiene at preventing hijacking](https://security.googleblog.com/2019/05/new-research-how-effective-is-basic.html), Google Security Blog
21. [Mobile Communications Best Practice Guidance](https://www.cisa.gov/resources-tools/resources/mobile-communications-best-practice-guidance), CISA
22. [Crypto](https://nodejs.org/api/crypto.html), Node.js documentation
23. [Errata for RFC 6238](https://www.rfc-editor.org/errata/rfc6238), RFC Editor
24. [RFC 9470: OAuth 2.0 Step Up Authentication Challenge Protocol](https://www.rfc-editor.org/rfc/rfc9470.html), IETF
