research/totp-codes-against-the-rfc-test-vectors

Six-Digit Sign-In Codes in Node.js: TOTP Checked Against the RFC Test Vectors, With a Drift Window and Replay Protection

Engineering Note · December 3, 2026 · 8 minute read · Security · Node.js · Authentication · Testing

The six-digit codes from an authenticator app are TOTP (Time-based One-Time Password): an HMAC of the current 30-second time step, using a secret the app and the server share, cut down to six digits. A dozen lines of Node.js generate them. Our version passed all 18 test vectors in RFC 6238 and all 10 HOTP vectors in RFC 4226, but only after one surprise. The RFC’s text names a 20-byte test secret, while its reference code uses 32-byte and 64-byte secrets for SHA-256 and SHA-512. With the 20-byte secret, 12 of the 18 vectors failed. We then added the two things a verifier needs beyond the math: a small window for clock drift, and a record of the last step used so a code cannot be accepted twice.

Everything below was run on Linux 6.18 with Node.js 22.23.5, using only node:crypto. The outputs are real.

What is a TOTP code made of?

TOTP is a thin layer over HOTP, the counter-based one-time password from RFC 4226. HOTP takes a secret key and an 8-byte counter, computes an HMAC, and uses “dynamic truncation” to pick four bytes of the result and turn them into digits. TOTP replaces the counter with the number of 30-second steps since 1970.

import { createHmac } from 'node:crypto';

// RFC 4226 section 5: HMAC over an 8-byte big-endian counter, then dynamic truncation.
export function hotp(key, counter, { digits = 6, algo = 'sha1' } = {}) {
  const msg = Buffer.alloc(8);
  msg.writeBigUInt64BE(BigInt(counter));
  const mac = createHmac(algo, key).update(msg).digest();
  const offset = mac[mac.length - 1] & 0x0f;
  const bin = mac.readUInt32BE(offset) & 0x7fffffff;
  return String(bin % 10 ** digits).padStart(digits, '0');
}

// RFC 6238 section 4: T = floor((now - T0) / X), default X = 30, T0 = 0.
export const step = (unixSeconds, x = 30) => Math.floor(unixSeconds / x);
export const totp = (key, unixSeconds, opts) => hotp(key, step(unixSeconds), opts);

Three details are easy to get wrong. The counter is 64-bit big-endian, so a 32-bit write passes today and fails for very large step counts. The & 0x7fffffff drops the top bit so the number is never negative. And padStart keeps leading zeros: 07081804 is a valid code.

Does it match the RFC 4226 vectors?

RFC 4226 Appendix D lists the six-digit HOTP values for counters 0 to 9 with the ASCII secret 12345678901234567890:

$ node hotp-vectors.mjs
755224 287082 359152 969429 338314 254676 287922 162583 399871 520489
all 10 match RFC 4226 Appendix D

Why did 12 of the 18 TOTP vectors fail at first?

RFC 6238 Appendix B gives eight-digit codes at six timestamps for SHA-1, SHA-256 and SHA-512, and says “the test token shared secret uses the ASCII string value ‘12345678901234567890’.” We used exactly that for all three:

$ node vectors.mjs naive
FAIL t=59 sha256: got 32247374, want 46119246
FAIL t=59 sha512: got 69342147, want 90693936
FAIL t=1111111109 sha256: got 34756375, want 68084774
FAIL t=1111111109 sha512: got 63049338, want 25091201
FAIL t=1111111111 sha256: got 74584430, want 67062674
FAIL t=1111111111 sha512: got 54380122, want 99943326
FAIL t=1234567890 sha256: got 42829826, want 91819424
FAIL t=1234567890 sha512: got 76671578, want 93441116
FAIL t=2000000000 sha256: got 78428693, want 90698825
FAIL t=2000000000 sha512: got 56464532, want 38618901
FAIL t=20000000000 sha256: got 24142410, want 77737706
FAIL t=20000000000 sha512: got 69481994, want 47863826
6 passed, 12 failed

The SHA-1 rows passed and every other row failed. The answer is in the Java reference code in Appendix A of the same RFC. It uses a 20-byte seed for HMAC-SHA1, a 32-byte seed32 for HMAC-SHA256 and a 64-byte seed64 for HMAC-SHA512, each made by repeating the digits 1234567890. With those keys:

const ascii = '12345678901234567890';
const seeds = {
  sha1: Buffer.from(ascii),
  sha256: Buffer.from(ascii.repeat(2).slice(0, 32)),
  sha512: Buffer.from(ascii.repeat(4).slice(0, 64)),
};
$ node vectors.mjs
18 passed, 0 failed

If your TOTP code fails only the SHA-256 and SHA-512 vectors, check the key length before you check the algorithm. Even if your app only ever uses SHA-1, run all 18 rows: the SHA-1 rows alone would not have shown this key-handling difference.

How does the secret get into the app?

The secret is random bytes. RFC 6238 says keys “SHOULD be randomly generated,” and crypto.randomBytes(20) does that. To show it to a person or put it in a QR code, apps use base32 (RFC 4648), which uses only capital letters and the digits 2 to 7, so there is no confusion between 0 and O or 1 and I.

Node.js has no built-in base32, so we wrote one in about 20 lines and tested it against the RFC 4648 section 10 vectors and 10,000 random round trips:

$ node b32test.mjs
""                    ok
"f"       MY          ok
"fo"      MZXQ        ok
"foo"     MZXW6       ok
"foob"    MZXW6YQ     ok
"fooba"   MZXW6YTB    ok
"foobar"  MZXW6YTBOI  ok
GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ
12345678901234567890
10000 random round trips, 0 failures

The decoder ignores spaces, hyphens, = padding and lowercase. The last test line decodes gezd gnbv gy3t qojq gezd gnbv gy3t qojq, the way a person might type a secret they read off a screen. Being forgiving here costs nothing and saves a support call.

How much clock drift should the verifier accept?

A phone’s clock is rarely exact, and a code typed at second 29 may arrive at second 31. RFC 6238 section 5.2 says “We RECOMMEND that at most one time step is allowed as the network delay.” Section 5.2 also says the verifier “MUST NOT accept the second attempt of the OTP after the successful validation has been issued for the first OTP.” Both fit in one function:

export function verify(key, code, nowSeconds, user, { window = 1 } = {}) {
  if (!/^\d{6}$/.test(code)) return { ok: false, why: 'format' };
  const now = step(nowSeconds);
  for (let d = -window; d <= window; d++) {
    const t = now + d;
    const expected = hotp(key, t);
    if (timingSafeEqual(Buffer.from(expected), Buffer.from(code))) {
      if (user.lastStep !== undefined && t <= user.lastStep) return { ok: false, why: 'replay' };
      user.lastStep = t;
      return { ok: true, drift: d };
    }
  }
  return { ok: false, why: 'no match' };
}

We fixed the server clock at Unix time 1,800,000,015 (15 seconds into a step) and generated codes from phones whose clocks were off by different amounts:

$ node verifytest.mjs
phone clock offset -> result (window = 1)
 -95s {"ok":false,"why":"no match"}
 -61s {"ok":false,"why":"no match"}
 -45s {"ok":true,"drift":-1}
 -16s {"ok":true,"drift":-1}
   0s {"ok":true,"drift":0}
  14s {"ok":true,"drift":0}
  15s {"ok":true,"drift":1}
  44s {"ok":true,"drift":1}
  45s {"ok":false,"why":"no match"}
  75s {"ok":false,"why":"no match"}
first use  {"ok":true,"drift":0}
same code  {"ok":false,"why":"replay"}
older code {"ok":false,"why":"replay"}
next step  {"ok":true,"drift":0}

With one step either side, three codes are valid at any moment, covering 90 seconds of phone time. Where the edges fall depends on where in the step the check lands: here a phone 45 seconds slow passed and one 45 seconds fast did not. The drift value is worth logging. A user whose codes always arrive at -1 has a slow phone clock, and RFC 6238 section 6 suggests recording that drift rather than widening the window for everyone.

The replay lines show the second rule. Once a code from a step has worked, that code fails, and so does any code from an earlier step, even though both are still inside the window. A code from the next step works normally. In a real app, user.lastStep belongs in the database with the user, updated in the same write that records the sign-in.

What else does a verifier need?

Six digits is a million possibilities, and a window of three valid codes makes a random guess succeed about 3 times in a million. RFC 4226 section 7.3 recommends a throttling parameter, a maximum number of failed attempts, and says it “SHOULD be set as low as possible, while still ensuring that usability is not significantly impacted.” Count failures per user, lock or slow down after a handful, and alert the account owner. The fixed-window counter in our note on rate-limiting a contact form works for this too.

Two more habits:

  • Compare in constant time. timingSafeEqual takes the same time whether the first digit or the last one differs. Its arguments must be the same length, which the format check guarantees.
  • Store the secret like a password you can read back. Unlike a password hash, the server needs the raw secret to compute codes. Encrypt it at rest and keep the encryption key out of the database, as RFC 6238 R7 asks that keys “SHOULD be protected against unauthorized access and usage.”

For when this matters to a business, and why a team should turn on two-step sign-in everywhere it is offered, see today’s article on passwords and logins for a small team.

Limitations

  • We tested against the RFC test vectors and our own generator. We did not scan a QR code into a real authenticator app or compare codes with one.
  • The otpauth:// URI that QR codes carry is not covered here; we did not test its format or how apps parse it.
  • user.lastStep was kept in memory. In production it needs to be stored and updated atomically, or two requests at the same moment could both pass the replay check.
  • We did not build throttling, encryption of stored secrets or recovery codes, all of which a real sign-in flow needs.
  • TOTP codes can be phished: a fake sign-in page can ask for a code and pass it on within the window. Nothing in this note protects against that, and we did not test phishing-resistant methods.

Sources

Frequently asked questions

How do authenticator app codes work?

The app and the server share a secret key, set up once by scanning a QR code. Every 30 seconds both compute an HMAC of the current time step with that key and turn it into a six-digit number. If the numbers match, the person holding the phone has the key. The method is TOTP, defined in RFC 6238 on top of HOTP from RFC 4226.

Why do my TOTP test vectors fail for SHA-256 and SHA-512?

Most likely the key length. The RFC 6238 text describes the test secret as the ASCII string 12345678901234567890, which is 20 bytes, but its reference code uses a 32-byte key for SHA-256 and a 64-byte key for SHA-512, made by repeating those digits. In our test the 20-byte key passed the SHA-1 rows and failed all 12 SHA-256 and SHA-512 rows.

How much clock drift should a TOTP check allow?

RFC 6238 recommends allowing at most one time step for network delay. With 30-second steps and one step either side, our verifier accepted codes from a phone clock between 45 seconds slow and 44 seconds fast, depending on where in the step the check fell. A wider window accepts more guesses.

Can a TOTP code be used twice?

It must not be. RFC 6238 says a verifier must not accept a second attempt with the same code after a successful one. Our verifier stores the last time step that succeeded for each user and refuses that step and any earlier one.

Should a small business build its own two-factor sign-in?

Usually not. If a sign-in system or hosted identity provider offers two-factor, use it. Writing the code yourself is worth it when you are adding a second factor to an app you already run, and then the RFC test vectors are the first test to write.

More from Research

← All research