Skip to content
Trapdoor·Lab

One-time codes: HOTP, TOTP and YubiKey

1Toy

A code from a secret and a counter

The code in an authenticator app does not come from the server. The phone and the server know the same secret K — usually 20 bytes that pass through a QR code when you turn on two-step verification — and each computes the code on its own. HOTP (RFC 4226, §5.3) takes a counter C, writes it as 8 bytes and computes HMAC-SHA-1(K, C). Of the 20 bytes of the MAC, 4 remain: the low 4 bits of the last byte say which byte to start from — the “dynamic truncation”. The top bit of those 4 bytes is cleared, and the remainder of division by 10⁶ is the six-digit code. TOTP (RFC 6238, §4) is the same HOTP with the number of a time window as the counter: T = ⌊Unix time / 30⌋. The clock replaces the counter, so the phone and the server have nothing to agree on — it is enough that both know the time. The “RFC 4226 secret” button enters the secret of appendix D: counter 0 gives 755224, and the time 59 s with 8 digits gives 94287082, as in the RFC 6238 table.

HOTP and TOTP step by step

20 / 64 B

This is how a service shows the secret when you turn on two-step verification: bytes written in base32 (RFC 4648), usually next to a QR code. A random one has 20 B from crypto.getRandomValues — what RFC 4226 recommends.

This is not base32 or it is longer than 64 B. Allowed are the letters A–Z and the digits 2–7; spaces and “=” do not matter.

K hex7b3c402df0b2bf4160e7f3460e6bc6e6292b9f98
HMAC function
Code length
Time

Computing the HMAC…

A YubiKey from the shop has a different scheme in slot 1: Yubico OTP. A touch of the button types 44 characters, like a keyboard. The first 12 are the key’s plain identifier (public id); the rest is one AES-128 block written in ModHex: 16 bytes with a secret private id, two counters, a timestamp, a random number and a CRC checksum (Yubico, “OTPs Explained”). ModHex uses only the letters cbdefghijklnrtuv, which sit in the same place on most Latin QWERTY layouts, so the code types the same whatever the keyboard language. Instead of an HMAC there is a cipher: the server decrypts the block, checks the CRC and the private id, and compares the counters with the last accepted code. To be honest: from the factory slot you can read only the public id. Yubico uploaded its AES key to its YubiCloud service at manufacturing, and secrets cannot be extracted from the hardware key (Yubico .NET SDK, “Yubico OTP”). You will see the whole breakdown on an example made in the browser, or on your own key if you program its slot 2 with an AES key you know.

Yubico OTP: one AES block

A key programmed here: a random public id, private id and AES-128 key, as with your own slot. Every touch is a new code.

public id
vnbntdlcbjie
Private id
d2cd805c0655
KAES-128 key 16 B · known to the YubiKey and the validation server
00 baabc30612be71667da942de49c249a4

Touch the button to make the key type a code.

2Break it

Replay and relay

A one-time code is one-time only because the server remembers something. After accepting an HOTP code the server moves its counter past it (RFC 4226, §7.2). With TOTP it stores the window it accepted the code from, because RFC 6238 forbids accepting the same code a second time (§5.2). With Yubico OTP it remembers the counters of the last code. A recorded code the victim has already logged in with is therefore worthless — which is why replay has the status “resistant” in the graph. The toy below uses this station’s verifier: you see exactly what the server remembers and what refuses the replay.

Replay an intercepted code

You are on the attacker’s side: you recorded the code the victim has just logged in with, and you send it again.

The victim’s token and the server count separately. The server accepts the code of the counter it expects or of a few after it (the window of RFC 4226, §7.4), and moves its counter past the accepted code.

Victim
token counter: 0
The server remembers
next counter 0; accepts 0–3

Start with the victim logging in — then there is something to record.

That word has limits. A code the victim did not use — shown but not typed, or typed by a YubiKey into a chat window — is valid for whoever uses it first: a TOTP code until the end of the server’s window, HOTP and Yubico OTP until a newer code is accepted. That is why Yubico advises “burning” such a code by submitting a newer one. The second attack builds on this: a fake site replays nothing, it relays the code to the real site before the victim does. This is what the 2022 attack on Cloudflare and Twilio employees looked like — the phishing page asked for a TOTP code and passed it straight on to the attacker.

A relay on a fake site

You are on the attacker’s side: you run a look-alike site and relay what the victim types to the real site, live.
Real site
trapdoorlab.app
Your fake
trapdoor1ab.example

Simulation: the network and both sites run in this tab. The victim’s code and the real site’s verifier are real — the same functions as in the replay toy.

The victim clicked a link in a text message and sees your fake. In a moment they will type a password and a code.

Nothing in the code depends on the site’s address: the HMAC is computed from K and the counter, the AES block from the key’s fields. That is why realtime-phishing has the status “vulnerable if misused”, and the misuse is treating a one-time code as protection against phishing. NIST says plainly that OTP authentication is not phishing-resistant (SP 800-63B, §3.1.4). Resistance comes only with a binding to the domain: a passkey signs the challenge together with the site’s address, and the browser will not hand a passkey to a foreign domain.

3In the real world

Where one-time codes work

  • Authenticator appsA service shows a QR code with an otpauth://totp/… address that carries the secret in base32. The format described by Google defaults to SHA1, 6 digits and a period of 30 s — that is, TOTP from RFC 6238 with its recommended time step.Source (Authenticator apps)
  • YubiKey and YubiCloudKeys from the shop have Yubico OTP in the short-press slot, with a public id starting with “cccc”, and the secrets go to YubiCloud, which validates the codes, at manufacturing. Changing that slot cannot be undone; a code generated outside a login can be intercepted and used until the server sees a newer one.Source (YubiKey and YubiCloud)
  • Cloudflare and Twilio, 2022At least 76 Cloudflare employees received a text message with a link to a fake login page in less than a minute; three entered their credentials. The page also asked for a TOTP code and relayed everything to the attacker in real time. Cloudflare does not use TOTP codes but FIDO2 keys bound to the domain — the attacker’s login failed.Source (Cloudflare and Twilio, 2022)
  • NIST SP 800-63BNIST’s guidelines: the verifier accepts a given code only once while it is valid, protects the symmetric keys against disclosure and disables the authenticator after at most 100 consecutive failed attempts. A one-time code is not phishing-resistant, and the highest level (AAL3) requires such resistance.Source (NIST SP 800-63B)
4Take it to your project

Remember the used code, do not promise phishing protection

Good practice

Make the secret from 20 random bytes of a CSPRNG (the Randomness station) and keep it encrypted: the server knows the same secret as the phone, so a database leak leaks the second factor of every account. Accept a code from the current window and the one before, store the last accepted window in the same transaction as the login, and refuse a code from a window that was already used. Limit failed attempts (RFC 4226, §7.3); NIST allows at most 100 in a row. Treat a one-time code as a second factor, and where phishing matters, offer passkeys.

JavaScript
import { createHmac, timingSafeEqual } from 'node:crypto';

function totp(secret, step) {
  const msg = Buffer.alloc(8);
  msg.writeBigUInt64BE(BigInt(step));
  const mac = createHmac('sha1', secret).update(msg).digest();
  const offset = mac[mac.length - 1] & 0x0f;
  return String((mac.readUInt32BE(offset) & 0x7fffffff) % 1e6).padStart(6, '0');
}

// read user.lastStep from the database and write it back in the same transaction as the login
function verify(user, code, now = Date.now()) {
  if (!/^\d{6}$/.test(code)) return false;
  const t = Math.floor(now / 1000 / 30);
  for (const step of [t, t - 1]) {
    if (step <= user.lastStep) continue; // this window was already used: a replay
    if (timingSafeEqual(Buffer.from(totp(user.secret, step)), Buffer.from(code))) {
      user.lastStep = step;
      return true;
    }
  }
  return false;
}
Anti-pattern

Do not accept the same code twice and do not widen the window “for convenience” — every extra window is another 30 s for an intercepted code (RFC 6238, §5.2). Do not check codes without a limit on attempts: six digits are a million possibilities, and a script without a limit walks them all. Do not keep TOTP secrets in plain text next to the password hashes. Do not tell users the code protects against phishing — a fake site relays it. Do not reprogram a YubiKey’s factory slot unless you want to lose its YubiCloud configuration.

JavaScript
// ✕ no memory of used windows, no limit on attempts, a window of ±10 steps
function verify(user, code, now = Date.now()) {
  const t = Math.floor(now / 1000 / 30);
  for (let step = t - 10; step <= t + 10; step++) {
    if (totp(user.secret, step) === code) return true;
  }
  return false;
}