Skip to content
Tutorials Center
My learning

Topics

Lesson 102 of 147 ยท Security

Two-Factor Auth and Passkeys

Implement TOTP two-factor authentication in PHP with hash_hmac and Base32, handle recovery codes and rate limits, and understand how passkeys and WebAuthn work.

A password alone is a weak lock. People reuse them, phishing pages steal them, and databases leak. Two-factor authentication (2FA) adds a second proof from a different category: something you know (password), something you have (phone, security key) or something you are (fingerprint). Even when the password is stolen, the attacker still needs the second factor.

This lesson implements the most common second factor, the time-based one-time password (TOTP) used by authenticator apps, in plain PHP. You will see how the six-digit codes are computed, verify our code against the official test vector from the RFC, add safeguards such as recovery codes and rate limiting, and then get an overview of passkeys and WebAuthn, the modern, phishing-resistant replacement for passwords. It builds on Password Hashing, Cryptography and Sessions.

How TOTP works

When a user enables 2FA, your server generates a random shared secret and shows it as a QR code. The authenticator app (Google Authenticator, Authy, 1Password, ...) stores it. From then on, both sides compute the same code independently from the secret and the current time, so nothing is sent over the network except the six digits the user types.

flowchart TD
    A["Shared secret (random bytes)"] --> C["HMAC-SHA1(secret, counter)"]
    T["Unix time / 30 seconds = counter"] --> C
    C --> D["Dynamic truncation: take 4 bytes at an offset"]
    D --> E["Modulo 10^6 = six digits"]

Server and phone run the same calculation; matching codes prove both hold the secret.

The algorithm is standardized in RFC 6238 (TOTP), built on RFC 4226 (HOTP):

  1. counter = floor(unix_time / 30), as an 8-byte big-endian integer.
  2. hash = HMAC-SHA1(secret, counter) (20 bytes).
  3. Dynamic truncation: the low 4 bits of the last byte give an offset; take the 4 bytes starting there, clear the top bit, and read them as a 31-bit integer.
  4. code = integer mod 10^digits, left-padded with zeros.

Authenticator apps almost always assume SHA-1, 6 digits and a 30-second step, so stick with those defaults even though SHA-1 is weak for other uses: inside an HMAC it is still fine.

Implementing TOTP

Secrets are shown to users as Base32 text (letters A to Z and digits 2 to 7), so we need a small Base32 encoder and decoder. PHP has none built in.

PHP TOTP checked against the RFC 6238 test vector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

All four lines match the RFC's published values, which is the standard way to prove a TOTP implementation is right. The six-digit code is simply the last six digits of the eight-digit one.

Verifying a code safely

A naive == check is not enough. A production verifier should:

  • Accept a small window. Phone clocks drift and users type slowly, so also try the previous and next 30-second steps (a window of plus or minus 1).
  • Compare in constant time with hash_equals().
  • Reject replays. Remember the last accepted time step per user and refuse codes from that step or earlier, otherwise someone who sees the code over a shoulder can reuse it for 30 seconds.
  • Rate limit. Six digits mean only a million possibilities, so lock or slow down after a few failures per user and per IP.
PHP Window, replay protection and lockout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In a real application, lastUsedStep and failures live in the database (or a cache such as Redis) next to the user record, never in memory.

Enrollment: secrets, QR codes and storage

  1. Generate 20 random bytes with random_bytes(20) and Base32-encode them.
  2. Show the secret as a QR code encoding an otpauth:// URI, plus the text secret for manual entry:
TEXT
otpauth://totp/Example%20Shop:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Example%20Shop&algorithm=SHA1&digits=6&period=30
  1. Ask for one valid code before you switch 2FA on, so a typo cannot lock the user out.
  2. Store the secret encrypted (for example with sodium or OpenSSL AES-GCM, see Cryptography), because you need the raw value to verify codes. A password hash would not work here.

Do not send the QR code through a third-party image service: the URL would contain the secret. Render QR codes on your server or in the browser.

Recovery codes

Phones get lost. At enrollment, create about ten single-use recovery codes, show them once, and store only their hashes. Treat them like passwords:

PHP Recovery codes that are stored hashed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Recovery codes are a back door, so rate-limit them like passwords, notify the user when one is used, and offer to generate a new set.

Other second factors

Factor Pros Cons
SMS code Easy for users SIM swapping, phishable, costs money
TOTP app Offline, standard Phishable (user can type the code into a fake site)
Push approval Convenient Prompt fatigue attacks
Security key / passkey Not phishable Needs hardware or a modern device

SMS is better than nothing but the weakest option, so offer authenticator apps first. Note that all code-based factors can be relayed by a real-time phishing proxy. That is the problem passkeys solve.

Passkeys and WebAuthn

WebAuthn is a browser API (with the CTAP protocol for external keys) that lets a website sign in a user with public-key cryptography instead of a shared secret. A passkey is a WebAuthn credential that the platform (iOS, Android, Windows, a password manager) can sync between a user's devices.

The key idea: each site gets its own key pair. The private key never leaves the authenticator; the server stores only the public key. Signing in means signing a fresh server challenge. Because the browser includes the site's real origin in what is signed, a look-alike phishing domain gets a useless signature. There is nothing to leak from your database and nothing for users to type.

sequenceDiagram
    participant U as User + authenticator
    participant B as Browser
    participant S as Your PHP server
    Note over U,S: Registration
    S->>B: challenge, relying party id, user info
    B->>U: navigator.credentials.create()
    U->>U: Create key pair, unlock with biometric or PIN
    U->>S: public key, credential id (via browser)
    S->>S: Verify, store public key
    Note over U,S: Sign-in
    S->>B: new random challenge
    B->>U: navigator.credentials.get()
    U->>S: signature over challenge + origin + counter
    S->>S: Verify with stored public key

Registration stores a public key; each sign-in proves possession of the matching private key by signing a new challenge.

The browser side uses a few lines of JavaScript (read-only here, because the sandboxed preview cannot talk to authenticators):

JavaScript
// Sign-in on the client. The server sent options as JSON.
const credential = await navigator.credentials.get({
  publicKey: {
    challenge: base64urlToBuffer(options.challenge), // random, from the server
    rpId: 'example.com',
    userVerification: 'preferred',
    allowCredentials: [], // empty = discoverable credential (passkey picker)
  },
});
// Send credential.id, authenticatorData, clientDataJSON and signature to the server.

The server side must verify the response: decode clientDataJSON and check the type, the challenge and the origin; check the hash of the relying-party ID in authenticatorData and the "user present" flag; check the signature with the stored public key; and update the stored signature counter. That is delicate binary parsing (CBOR, COSE keys, ASN.1), so in PHP use a maintained library such as web-auth/webauthn-lib or lbuchs/webauthn rather than writing it yourself.

Design advice for adding passkeys:

  • Keep passwords as a fallback at first, and offer "create a passkey" after a successful sign-in.
  • Store a list of credentials per user (several devices), each with ID, public key, counter, label and last-used time.
  • Allow users to remove lost devices; never allow removing the last way to sign in without a recovery path.
  • Use HTTPS and a fixed relying-party ID (your domain). Passkeys do not work on plain HTTP except localhost.
  • A passkey that is user-verified (biometric or PIN) is both "something you have" and "something you are", so it can replace password plus 2FA in one step.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What do the server and the authenticator app both use to compute the same TOTP code?

    TOTP derives the code from HMAC(secret, floor(time / 30)). Nothing is transmitted except the digits the user types.
  2. 2. Why should the server remember the last accepted time step?

    Without it, an observed code could be reused for the rest of its validity window.
  3. 3. How should recovery codes be stored?

    They are equivalent to a password for bypassing 2FA, so only hashes are stored and each code works once.
  4. 4. Why are passkeys resistant to phishing?

    The browser binds the assertion to the site's origin and the private key never leaves the authenticator.

Summary

  • 2FA combines a password with a second factor; TOTP is the common free option for authenticator apps.
  • TOTP is HMAC-SHA1(secret, floor(time / 30)), dynamically truncated to 6 digits; verify your implementation against the RFC 6238 vectors.
  • Verify with a small time window, hash_equals(), replay protection and rate limiting. Store secrets encrypted and recovery codes hashed.
  • Prefer authenticator apps or security keys over SMS.
  • Passkeys (WebAuthn) replace shared secrets with per-site key pairs: the server stores only public keys, and phishing does not work. Use a maintained PHP library for server-side verification.

Next up: Generators.