DEV Community

Dev Nestio
Dev Nestio

Posted on

Build a Browser-Only TOTP 2FA Generator with Web Crypto API

I built a TOTP (RFC 6238) generator that runs entirely in the browser — no server, no dependencies, just the Web Crypto API.

Try it: https://devnestio.pages.dev/totp-generator/

How TOTP works

TOTP = HMAC(secret, counter) where counter = floor(epoch / period).

Key implementation

async function generateTOTP(secret, algorithm, digits, period) {
  const keyBytes = base32Decode(secret);
  const counter = Math.floor(Date.now() / 1000 / period);
  const counterBuf = new Uint8Array(8);
  let tmp = counter;
  for (let i = 7; i >= 0; i--) { counterBuf[i] = tmp & 0xff; tmp = Math.floor(tmp / 256); }
  const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: algorithm }, false, ["sign"]);
  const sig = await crypto.subtle.sign("HMAC", key, counterBuf);
  const hash = new Uint8Array(sig);
  const offset = hash[hash.length - 1] & 0x0f;
  const code = (((hash[offset] & 0x7f) << 24) | (hash[offset+1] << 16) | (hash[offset+2] << 8) | hash[offset+3]) % Math.pow(10, digits);
  return String(code).padStart(digits, "0");
}
Enter fullscreen mode Exit fullscreen mode

Features

  • SHA-1, SHA-256, SHA-512 algorithms
  • 6 or 8 digit codes, 30s or 60s periods
  • Visual countdown progress bar (turns red at 5s)
  • Generate random secrets via crypto.getRandomValues
  • All processing browser-only

Source: Single HTML file, zero dependencies. Check out DevNestio for more browser tools.

Top comments (0)