Two-factor authentication and one-time codes

Introduction

When you sign in to a mobile wallet on a new phone, it usually asks for more than your PIN: a one-time code sent by SMS, or a code from an app. That second step is two-factor authentication (2FA). Even if someone has watched you type your PIN, they still need something only you have.

This lesson explains the kinds of factors, how authenticator apps make a new 6-digit code every 30 seconds without any network connection, and which kinds of 2FA resist phishing.

How it works

Proofs of identity come in three kinds, called factors:

FactorExamplesStolen by
Something you knowPassword, PINPhishing, shoulder surfing, leaks
Something you havePhone, security keyTheft, SIM swap
Something you areFingerprint, faceHard to steal remotely, impossible to change if copied

Two-factor means two different kinds. A password plus a security question is still one factor (two things you know).

Authenticator apps use TOTP (time-based one-time password, RFC 6238). When you set it up, the site and your phone share a secret key, usually through a QR code. From then on, both compute the same code on their own:

  1. counter = floor(seconds since 1 January 1970 ÷ 30), so the counter goes up by one every 30 seconds.
  2. Compute HMAC-SHA-1(secret, counter), a keyed hash that only someone with the secret can produce.
  3. Dynamically truncate the 20-byte result to a 31-bit number, and keep its last 6 decimal digits.

No message is sent: the phone and the server agree because they share the secret and the clock. Servers usually accept the codes from one step before and after, in case a clock has drifted. The older HOTP (RFC 4226) is the same idea with a counter that goes up each time a code is used, instead of the time.

// TOTP: the code changes every 30 seconds because it is computed from a counter,
// counter = floor(seconds since 1 January 1970 / 30). Phone and server compute it separately.
const step = 30;
for (const t of [59, 60, 1111111109, 1111111111]) {
  const counter = Math.floor(t / step);
  const left = step - (t % step);
  console.log("time " + t + ": counter " + counter + ", code changes in " + left + " s");
}
Open in compiler

At time 59 the counter is 1, and one second later it becomes 2, so the code changes. These times come from the test table in RFC 6238.

Example

The truncation step is the clever part: it picks where to read from the hash using the hash itself. The HMAC value below is the worked example printed in RFC 4226.

// HOTP's "dynamic truncation" (RFC 4226): turn a 20-byte HMAC-SHA-1 result into a 6-digit code.
// This HMAC value is the worked example printed in the RFC itself.
const hmac = "1f8698690e02ca16618550ef7f19da8e945b555a";
const bytes = [];
for (let k = 0; k < hmac.length; k += 2) bytes.push(parseInt(hmac.slice(k, k + 2), 16));

const offset = bytes[19] & 0x0f; // the last 4 bits pick where to read
const number =
  ((bytes[offset] & 0x7f) << 24) | (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3];
console.log("offset " + offset + ", 31-bit number " + number);
console.log("6-digit code: " + String(number % 1000000).padStart(6, "0"));
Open in compiler

Line by line

  1. The 40 hex digits are turned into 20 bytes.
  2. The last byte is 0x5a; its low 4 bits (& 0x0f) are 0xa, so the offset is 10.
  3. The four bytes from position 10 are 50 ef 7f 19. The first is masked with 0x7f to drop its top bit, so the result is a positive 31-bit number: 0x50ef7f19 = 1357872921.
  4. % 1000000 keeps the last six digits, 872921, padded to six digits if needed. This is the code the RFC gives.

Expected result

offset 10, 31-bit number 1357872921
6-digit code: 872921

In the real world

  • SMS codes are better than nothing but are the weakest form: a SIM swap (an attacker persuades a mobile operator to move your number to their SIM) sends your codes to them.
  • Authenticator app codes cannot be swapped like that, but a fake login page can still ask you for the code and use it at once, within the 30 seconds.
  • Security keys and passkeys (FIDO2 and WebAuthn) are phishing-resistant: the key signs a challenge that includes the real site's address, so a look-alike site gets nothing it can use.
  • Attackers sometimes send repeated "approve this sign-in?" prompts, hoping a tired user taps yes. Number matching, where you type a number shown on the login screen, defeats this.

Common mistakes

  • Sharing a one-time code with someone who calls you. Real banks and wallets never ask for it; a caller who does is the attacker.
  • Thinking two passwords make two factors. They are the same kind.
  • Keeping no backup codes. A lost phone can lock you out; store recovery codes safely.
  • Building 2FA without rate limits. A 6-digit code has only a million values, so unlimited guessing defeats it.

Best practices

  • Turn on 2FA for e-mail, banking and wallets first: e-mail can reset everything else.
  • Prefer passkeys or security keys, then authenticator apps, then SMS.
  • As a developer, limit code attempts, accept only a small clock window, and never reuse a code.
  • Protect the TOTP secret on the server like a password: whoever has it can make codes.

Summary

Two-factor authentication asks for two different kinds of proof, such as something you know and something you have. Authenticator apps implement TOTP: the phone and server share a secret, compute a counter from the time every 30 seconds, take an HMAC of it and truncate the result to six digits, so both produce the same code without talking. SMS codes can be stolen by SIM swaps and any typed code can be phished, while passkeys and security keys bind the login to the real site. Rate limits keep short codes safe.

Quick check

1. A site asks for a password and then the name of your first school. How many factors is that?
2. At Unix time 1111111111, what is the TOTP counter with a 30-second step?
3. Why are passkeys and security keys called phishing-resistant?
4. Why must a server limit how many 2FA codes can be tried?

Key takeaways

  • Two factors must be two different kinds: know, have, are.
  • TOTP codes come from HMAC(secret, floor(time ÷ 30)), so phone and server agree without talking.
  • SMS codes can be stolen by SIM swaps, and typed codes can be phished; passkeys resist both.
  • Short codes need rate limits and a small clock window on the server.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.