HomeGuidesHow to Generate TOTP Two-Factor Authentication Codes (RFC 6238)
Security & Privacy8 min readUpdated 2026-11-07

How to Generate TOTP Two-Factor Authentication Codes (RFC 6238)

Understand the cryptographic mathematics behind Google Authenticator, 30-second Unix time slices, and HMAC-SHA1 dynamic truncation.

Need to do this immediately?

Use our free, private client-side browser tool with zero installation.

Launch In-Browser HMAC & Cryptography Suite
Two-Factor Authentication (2FA) apps like Google Authenticator and 1Password generate fresh 6-digit codes every 30 seconds—even when your phone is in Airplane Mode with zero cellular or Wi-Fi connectivity. This seamless offline security is powered by RFC 6238 Time-Based One-Time Password (TOTP) mathematics.

The 30-Second Time Counter Math

TOTP is built on HMAC-based One-Time Passwords (HOTP, RFC 4226). While HOTP increments an event counter on every login, TOTP derives its counter directly from the current Unix epoch time in seconds: Counter = floor(UnixTime / 30).

Because both your smartphone and the authentication server have internal quartz clocks synchronized to UTC, both parties calculate the identical integer counter at any given second without needing to communicate over the network.

HMAC-SHA1 and Dynamic Truncation

The counter integer (packed as an 8-byte big-endian buffer) and your Base32-decoded secret key are fed into an HMAC-SHA1 algorithm, yielding a 20-byte cryptographic hash.

Dynamic truncation takes the last 4 bits of the hash as an offset, extracts a 31-bit unsigned integer from that offset, and computes integer modulo 1,000,000 to produce the final 6-digit verification code.

Pro Tip:When backing up 2FA secrets, save the Base32 alphanumeric seed in an encrypted zero-knowledge password vault.

Step-by-Step Tutorial

1

Read Current Unix Timestamp

Divide Math.floor(Date.now() / 1000) by 30 to calculate the current time counter window.

2

Compute HMAC-SHA1 Digest

Hash the 8-byte counter buffer with your shared Base32 secret using Web Crypto API.

3

Extract 6-Digit Verification Code

Perform 4-byte dynamic truncation and take modulo 10^6 to display the live 6-digit code.

Ready to Try It Yourself?

DocSwift processes everything directly on your device. Fast, safe, and completely free forever.

How helpful was this guide?

Rated 4.9 / 5 by 3,420+ users worldwide

Share with Colleagues & Friends

Help others protect their document privacy

Frequently Asked Questions

Why does TOTP work without an internet connection on my phone?

Because the calculation requires only the shared secret seed and the current Unix timestamp from your device hardware clock. No network communication is involved.

What happens if my device clock is slightly out of sync?

RFC 6238 servers routinely evaluate the previous counter window (-30s) and next window (+30s) to tolerate minor client clock drifts of ±1 minute.