How TOTP Two-Factor Codes Work, and Why They Sometimes Fail

Understand how authenticator apps turn a shared secret and the current time into a six-digit code, what otpauth links contain, and how to fix rejected codes.

Updated September 29, 2026 6 min read

Use the free TOTP / 2FA Code GeneratorGenerate 2FA codes from a secret, create secrets and authenticator QR codes

You scan a QR code with an authenticator app, and from then on it shows a new six-digit code every 30 seconds. The app works on a phone in flight mode, yet the website somehow knows which code is correct. Then one day the codes stop being accepted, and you have no idea whether the problem is the phone, the app or the account.

This guide explains what is inside that QR code, how a code is calculated from a secret and the clock, how TOTP differs from HOTP, and how to troubleshoot rejected codes. If you are a developer adding two-factor authentication to an application, it also shows how to generate and verify codes yourself.

The idea: a shared secret plus a moving number

TOTP stands for Time-based One-Time Password, defined in RFC 6238. It builds on HOTP (HMAC-based One-Time Password, RFC 4226). Both rely on the same principle:

  1. When you enable 2FA, the service creates a random secret key and shows it to you, usually as a QR code.
  2. Your authenticator app and the server both store that secret.
  3. To produce a code, each side feeds the secret and a moving number into an HMAC function and shortens the result to six digits.
  4. Because both sides use the same secret and the same moving number, they get the same code, without any network connection.

The only difference between the two standards is the moving number. HOTP uses a counter that increases each time a code is used. TOTP uses time: the number of 30-second steps since 1 January 1970 (Unix time).

How the code is calculated

For TOTP with the usual settings, the steps are:

T      = floor(current Unix time / 30)
hash   = HMAC-SHA1(secret, T as an 8-byte number)
offset = last 4 bits of hash
number = 4 bytes of hash starting at offset, top bit cleared
code   = number mod 1,000,000   (padded to 6 digits)

The "offset" step is called dynamic truncation; it picks four bytes from a position that changes with every hash. The same logic in Node.js looks like this:

const crypto = require("node:crypto");

function base32Decode(input) {
  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
  const clean = input.toUpperCase().replace(/[\s=-]/g, "");
  let bits = 0, value = 0;
  const out = [];
  for (const ch of clean) {
    const idx = alphabet.indexOf(ch);
    if (idx === -1) throw new Error("Invalid Base32 character: " + ch);
    value = (value << 5) | idx;
    bits += 5;
    if (bits >= 8) {
      out.push((value >>> (bits - 8)) & 0xff);
      bits -= 8;
    }
  }
  return Buffer.from(out);
}

function totp(secretBase32, { period = 30, digits = 6, algorithm = "sha1", time = Date.now() } = {}) {
  const counter = Math.floor(time / 1000 / period);
  const msg = Buffer.alloc(8);
  msg.writeBigUInt64BE(BigInt(counter));
  const hmac = crypto.createHmac(algorithm, base32Decode(secretBase32)).update(msg).digest();
  const offset = hmac[hmac.length - 1] & 0x0f;
  const binary = hmac.readUInt32BE(offset) & 0x7fffffff;
  return String(binary % 10 ** digits).padStart(digits, "0");
}

console.log(totp("JBSWY3DPEHPK3PXP"));

This reproduces the RFC 6238 test vectors (for example, the 8-digit SHA-1 code 94287082 at Unix time 59). For production code, prefer a maintained library over your own implementation, and compare codes with a constant-time comparison.

On Linux or macOS, the oathtool package gives you the same result from the command line:

oathtool --totp -b JBSWY3DPEHPK3PXP

What is inside the QR code

The QR code is just text: an otpauth:// URI in the key URI format popularised by Google Authenticator.

otpauth://totp/Northwind:alice@example.com?secret=JBSWY3DPEHPK3PXP&issuer=Northwind&algorithm=SHA1&digits=6&period=30
Part Meaning
totp Type; hotp would add a counter parameter
Northwind:alice@example.com Label shown in the app (issuer and account)
secret The shared key, Base32-encoded (letters A-Z and digits 2-7)
issuer Service name, used to group and label the entry
algorithm, digits, period Optional; SHA1, 6 and 30 are the defaults

Some authenticator apps ignore non-default algorithm, digit or period values, so the defaults are the safest choice for compatibility.

Generate and inspect codes with our tool

The TOTP Generator calculates codes with your browser's Web Crypto API; the secret is not sent anywhere. It is useful for testing your own 2FA implementation or understanding a setup link.

  1. Open the TOTP Generator. In Secret key (Base32) or otpauth:// URI, paste a Base32 secret, or paste a full otpauth:// link, which fills in every field automatically. To create a fresh secret for a test account, click Generate new secret.
  2. Check the options: Type (TOTP time-based or HOTP counter-based), Algorithm (SHA-1 standard, SHA-256 or SHA-512), Digits (6 or 8) and Period (30, 60 or 15 seconds). For HOTP, set the Counter instead.
  3. Read the Current code. The progress bar shows how many seconds remain, and the Previous and Next codes are shown too, which helps when testing how much clock drift your server tolerates.
  4. Under Set up an authenticator app, enter an Issuer (service name) and Account. The tool builds the otpauth:// URI and a QR code you can scan with your authenticator app, and shows the secret in groups of four for manual entry.
  5. Download the QR code as PNG or SVG if you need it in test documentation. For general-purpose QR codes, use the QR Code Generator.

Treat any real 2FA secret like a password: anyone who has it can generate your codes. Use test secrets for experiments, and don't paste production secrets into any website unless you are sure the tool runs entirely on your device.

Why codes get rejected

The clock is wrong

TOTP depends on both sides agreeing on the time. If your phone's clock is a minute off, its codes belong to a different time step. Turn on automatic date and time in the phone's settings. Most servers accept the code from one step before or after the current one to allow for small drift and typing delay, but not more.

The code expired while you typed

If there were only a couple of seconds left on the timer, wait for the next code rather than racing it.

The account was re-enrolled

If you set up 2FA again, the service generated a new secret. The old entry in your app now produces codes nobody accepts. Delete the stale entry and keep the new one.

Wrong settings

A secret created for SHA-256 or 8 digits produces different codes under default settings. Compare the settings in the otpauth link with what your app is using.

Security notes for developers

  • Generate secrets from a cryptographically secure random source. 20 bytes (160 bits) is the length RFC 4226 recommends for SHA-1; the Secret Key Generator can create random keys for other purposes.
  • Store TOTP secrets encrypted on the server. They are as sensitive as passwords, and unlike password hashes they must be recoverable to verify codes.
  • Reject a code that has already been used within its time window, and rate-limit attempts, because six digits is only a million possibilities.
  • Provide recovery codes, and never log secrets or codes. The underlying primitive is the same HMAC used for webhook signatures, and the HMAC Generator lets you experiment with it.

Frequently asked questions

Do authenticator apps need an internet connection?

No. The code depends only on the stored secret and the device's clock, so apps work offline. The clock does need to be accurate.

What is the difference between TOTP and HOTP?

TOTP derives the moving number from the current time, so codes expire every period. HOTP uses a counter that increases with each use, so a code stays valid until it is used.

Can I move my 2FA codes to a new phone?

Many apps offer an export or encrypted backup. Otherwise, sign in to each service, disable and re-enable 2FA, and scan the new QR code on the new phone.

Is it safe to generate TOTP codes in a browser?

It is fine for testing and development when the tool runs locally, as ours does. For your real accounts, keep secrets in a dedicated authenticator app or password manager.

Why are TOTP secrets in Base32?

Base32 uses only capital letters and digits 2-7, which avoids confusing characters and is easy to type manually when a QR code can't be scanned.

Try it now: TOTP / 2FA Code Generator

Loading tool…