How TOTP works — the RFC 6238 algorithm step by step

TOTP (Time-based One-Time Password) is an open standard (RFC 6238) for generating short-lived authentication codes that require no network communication between the authenticator and the server. When you scan a QR code to add an account to an authenticator app, both the server and your app receive the same shared secret — a random sequence of bytes encoded in Base32 (the uppercase alphabet A–Z plus digits 2–7). From that moment forward, they can independently generate the same codes on demand.

The algorithm works in three steps. First, divide the current Unix timestamp (seconds since January 1, 1970 UTC) by the time period (usually 30) and round down — this produces the time counter. Second, compute HMAC-SHA1 (or SHA-256/SHA-512 in newer deployments) of the counter represented as an 8-byte big-endian integer, using the secret as the HMAC key — this produces a 20-byte hash digest. Third, apply dynamic truncation: take the last nibble (4 bits) of the HMAC as an offset, extract 4 bytes starting at that offset, mask the high bit to avoid sign issues, and take the result modulo 10⁶ to produce a 6-digit code.

Because both the server and your app perform these same three steps simultaneously using the same secret and the same clock, they always arrive at the same 6-digit number — without any network round-trip required to validate. The code changes every 30 seconds regardless of whether it has been used. Most servers accept codes from the previous and next time window (±30 seconds) to accommodate slight clock drift between devices.

This tool implements the algorithm using the Web Crypto API — a native browser API available in every modern browser since 2015. Your secret key never leaves your device, never touches a server, and is not stored in localStorage or any other persistent storage. You can verify this by loading the page, disconnecting from the internet, and confirming the codes still refresh correctly.

TOTP vs HOTP vs SMS — understanding 2FA methods

Two-factor authentication (2FA) broadly means requiring a second proof of identity beyond the password. Several different OTP mechanisms exist, each with different security profiles, convenience trade-offs, and failure modes.

TOTP (Time-based OTP, RFC 6238)

Uses the current time divided by the period as the counter. Codes expire automatically even if unused — there is no state to synchronise between client and server. No network connectivity required to generate codes. Codes are valid for one time period on both sides (typically ±1 window). TOTP is the most widely deployed consumer 2FA mechanism, supported by Google, GitHub, AWS, Cloudflare, Binance, and thousands of other services.

HOTP (HMAC-based OTP, RFC 4226)

Uses a monotonically incrementing counter instead of time. The server and client advance the counter with each successful authentication. HOTP codes do not expire — they are valid indefinitely until used, which is both a convenience feature (no time pressure) and a security risk (a stolen code can be replayed until the server uses it). Counter drift is the main operational challenge: if codes are generated but not presented to the server, the client counter advances while the server's expectation does not, eventually causing authentication failure. HOTP appears in some hardware tokens (RSA SecurID, YubiKey OTP) and older enterprise deployments.

SMS OTP

Sends a one-time code to your phone via text message. Easy to use — no app, no setup, no secret to manage. However, SMS OTP is significantly weaker than TOTP: it is vulnerable to SIM-swapping attacks (criminals convince carriers to transfer your number to a SIM they control), SS7 network interception (a known vulnerability in the telephone signalling protocol used by carriers), and social engineering (impersonating the carrier to claim the number). NIST SP 800-63-3 (2017) deprecated SMS as a standalone 2FA method for federal systems. SMS OTP is far better than no 2FA, but should be replaced with TOTP or hardware keys wherever possible.

MethodStandardOfflinePhishing resistantSIM-swap safeRecommended
TOTPRFC 6238✗ (real-time relay possible)✓ Yes
HOTPRFC 4226⚠ Limited
SMS OTPNone✗ Avoid
FIDO2/WebAuthnW3C + FIDO2✓ (origin-bound)✓ Best

Authenticator apps compared — which one should you use?

All TOTP authenticator apps generate identical codes from the same secret — the algorithm is fully standardised. The differences are in backup, sync, export, platform support, and security model. Choosing the right app affects your recovery options when a device is lost.

AppPlatformsCloud backupExportOpen source
Google AuthenticatoriOS, AndroidGoogle Account (2023+, encrypted)Yes (to Google Account)
AuthyiOS, Android, DesktopAuthy cloud (encrypted)Limited
Microsoft AuthenticatoriOS, AndroidMicrosoft Account (encrypted)Yes (to same MS account)
Aegis (Android)Android onlySelf-hosted file (encrypted)Yes (JSON/URI)
Raivo (iOS)iOS onlyiCloud (encrypted)Yes (OTP Auth format)
Bitwarden AuthenticatoriOS, AndroidBitwarden cloud (E2E encrypted)Yes (JSON)
1PasswordAll platforms1Password cloud (E2E encrypted)Yes
KeePassXCDesktop (all OS)Local only (KeePass db)Yes (CSV/JSON)

For maximum recoverability, choose an app that supports both encrypted cloud backup and local export (Aegis for Android, Raivo or Bitwarden for iOS). For teams and enterprises, 1Password and Bitwarden both integrate TOTP into a password manager workflow, keeping codes and passwords in a single audited vault.

Setting up TOTP for a service — step by step

Enabling TOTP on an account is a one-time process that takes about two minutes. Here is the standard flow used by nearly every service that supports TOTP:

  1. 1
    Navigate to two-factor authentication settings
    Usually found under Account → Security → Two-Factor Authentication. Some services call it "Authenticator app," "TOTP," or "2-step verification."
  2. 2
    Choose "Authenticator app" (not SMS)
    Select the authenticator app option — not SMS. The service generates a TOTP secret and shows it as a QR code.
  3. 3
    Save the secret key
    Before scanning the QR code, look for a "Can't scan? Show the text key" option. Copy this Base32 secret and save it securely in your password manager. This is your recovery key if you lose your phone.
  4. 4
    Scan the QR code with your authenticator app
    Open your authenticator app, tap "Add account" or "+", then scan the QR code. The app now generates valid codes.
  5. 5
    Verify with a current code
    The service will ask you to enter a code from the app to confirm setup worked. Enter the current 6-digit code shown in your app.
  6. 6
    Save backup codes
    After enabling TOTP, the service provides one-time backup codes. Store these in your password manager in a different vault or print them. They are your emergency access if you lose your device.

TOTP backup and recovery — never get locked out

The most common TOTP disaster is losing access to your authenticator app — through a lost phone, a factory reset, or a broken device — and finding yourself locked out of accounts. The correct preventive measures:

Save the raw secret

When setting up TOTP, always save the text representation of the secret (the Base32 string shown under or beside the QR code). Store it in your password manager alongside the account credentials. With the raw secret, you can re-add the account to any authenticator on any device at any time — no customer support needed.

Use an authenticator with encrypted backup

Authy, 1Password, Bitwarden Authenticator, and Microsoft Authenticator all offer encrypted cloud sync. If your phone is lost, reinstall the app on a new device, log into your account, and your TOTP secrets are restored. Aegis (Android) lets you export an encrypted backup file and store it in Google Drive or another cloud service under your control.

Register multiple devices

Adding the same TOTP secret to two devices (e.g., your phone and a tablet) means both generate identical codes simultaneously. Losing one device does not lock you out — the other still works. This is the simplest recovery strategy that requires no additional software or cloud accounts.

Store backup codes securely

Most services provide 8–16 one-time backup codes when you enable 2FA. Each code can only be used once. Store them in your password manager in a separate vault from the TOTP secret itself, or print them and keep them in a physically secure location. Backup codes are the last resort when all other 2FA methods are unavailable — treat them like a skeleton key.

Implementing TOTP in your own application

If you are building a service that needs TOTP-based 2FA, the implementation is straightforward — the algorithm is a thin wrapper around HMAC-SHA1. Libraries exist for every major language.

Server-side libraries

Use battle-tested libraries rather than rolling your own: pyotp (Python), notp or otplib (Node.js), ROTP (Ruby), google/google-authenticator-libpam (C). These handle the edge cases of the algorithm correctly — particularly the 64-bit counter encoding and timing window calculations.

QR code URI format

TOTP accounts are transferred via the otpauth:// URI scheme. A full URI looks like: otpauth://totp/Service%20Name:user%40example.com?secret=BASE32SECRET&issuer=ServiceName&algorithm=SHA1&digits=6&period=30. Encode this URI as a QR code using any QR library to give users a scannable setup code. Include both issuer and the account name in the label so the authenticator app shows a useful description.

Security considerations for implementers

Always generate secrets with a cryptographically secure random number generator — at least 20 bytes (160 bits) of entropy. Rate-limit code verification attempts (lock after 5–10 failures). Mark each time-window code as used server-side to prevent replay attacks within the same 30-second window. Store secrets encrypted at rest using AES-256-GCM or equivalent; treat them with the same care as password hashes. Provide a secure mechanism for users to regenerate their secret (which invalidates all existing authenticator pairings) and to disable TOTP entirely via backup codes.

FAQ

Common questions

What is TOTP and how does it work?

TOTP (Time-based One-Time Password, RFC 6238) generates a short numeric code by combining a shared secret key with the current time. Both the server and your authenticator app independently compute HMAC-SHA1 (or SHA-256) of the current 30-second time window using the same secret. Because the math is deterministic, they produce the same 6-digit code without any network communication. The code changes every 30 seconds and each code can only be used once.

Is TOTP the same as Google Authenticator?

Google Authenticator is an app that implements TOTP (and HOTP). The underlying algorithm is an open standard (RFC 6238), not proprietary to Google. Any TOTP-compatible authenticator — Authy, Microsoft Authenticator, Bitwarden, 1Password, Aegis (Android), Raivo (iOS) — will generate identical codes from the same secret. You are not locked into Google Authenticator.

What is a TOTP secret key and how is it encoded?

A TOTP secret is a random sequence of bytes (typically 16–32 bytes for strong security) encoded in Base32 — the uppercase letters A–Z and digits 2–7. Base32 encoding is used because it avoids characters that are easily confused visually (unlike Base64 which includes 0/O and 1/l). When you scan a QR code to add an account to an authenticator, the secret is embedded in the QR code in a URI like otpauth://totp/service?secret=BASE32SECRET.

What happens when a TOTP code expires?

TOTP codes change every 30 seconds (the standard period). Most server implementations accept codes from the previous and next window (±30 seconds) to account for clock drift. If your device clock is significantly wrong, your TOTP codes will be out of sync with the server. Authenticator apps that support time sync (like Authy) automatically correct for minor drift. For testing, this tool uses your device's system time.

What is the difference between TOTP and HOTP?

TOTP (Time-based OTP) uses the current Unix time divided by the period (usually 30 seconds) as the counter. HOTP (HMAC-based OTP, RFC 4226) uses an incrementing counter — the server and client both advance the counter with each authentication. TOTP is more commonly used because time is automatically synchronised; HOTP can drift if the counter gets out of sync (e.g., if codes are generated but not used).

How secure is TOTP for two-factor authentication?

TOTP provides strong protection against password-only attacks because an attacker needs both your password and physical access to your device. However, TOTP is vulnerable to real-time phishing (an attacker proxies the login, relaying your code before it expires) and SIM-swapping (if the backup is SMS). For higher security, prefer hardware security keys (FIDO2/WebAuthn) which are phishing-resistant. TOTP is far better than SMS 2FA.

Can I use a 6-digit vs 8-digit TOTP code?

Both are supported by RFC 6238. Most services use 6 digits (10⁶ = 1,000,000 possible codes per 30-second window), but 8 digits (10⁸ = 100,000,000 possible codes) provide additional security. Rate limiting on the server side is more important than code length — most servers lock accounts after 3–5 failed attempts, making brute-force attacks on 6-digit codes impractical in the allotted time window.

Does this TOTP generator store my secret key?

No. This tool runs entirely in your browser — your secret key never leaves your device and is never sent to a server. The TOTP code is computed using the Web Crypto API (built into every modern browser) directly on the page. You can verify this by disconnecting from the internet and reloading — the tool will still work.

More in Security