TOTP 2FA Authenticator Simulator
Simulate live RFC 6238 time-based one-time password (TOTP) codes with rolling 30-second countdown timer from Base32 secrets.
Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.
What is a TOTP Authenticator Simulator?
A TOTP (Time-Based One-Time Password) Authenticator Simulator is a cryptographic verification and security diagnostics tool that implements the open algorithm standardized under RFC 6238 (which extends the HMAC-based One-Time Password algorithm RFC 4226 / HOTP).
TOTP is the universal, vendor-agnostic technology powering two-factor authentication (2FA / MFA) applications—including Google Authenticator, Microsoft Authenticator, 1Password, Bitwarden, and Apple iCloud Keychain.
In modern cybersecurity architectures, relying solely on static passwords exposes accounts to catastrophic credential stuffing and data breach dumps. TOTP introduces an independent authentication factor: something you have (a physical smartphone or cryptographic token holding a shared secret key). Every 30 seconds, the authenticator algorithm computes a fresh, synchronized 6-digit or 8-digit verification code. Because the code changes continuously and expires after half a minute, intercepted or stolen codes become instantly useless to unauthorized attackers.
The Cryptographic Mechanics of RFC 6238 & RFC 4226
The generation of a TOTP token relies on a deterministic five-stage mathematical pipeline combining Unix time, Base32 decoding, HMAC hashing, dynamic truncation, and modular reduction:
flowchart TD
SecretKey["Shared Secret Key (Base32 Encoded: JBSWY3DPEHPK3PXP)"] --> DecodeBase32["1. Base32 Decode to Raw Secret Bytes (K)"]
CurrentTime["Current Unix Timestamp: Seconds since 1970-01-01 UTC"] --> ComputeCounter["2. Compute Time Step Counter: C = floor(Time / 30)"]
ComputeCounter --> PackBigEndian["Pack Counter C into 8-byte Big-Endian Integer"]
DecodeBase32 & PackBigEndian --> HMAC["3. Compute HMAC-SHA1: HS = HMAC(K, C)"]
HMAC --> DynamicTruncate["4. Dynamic Truncation: Offset = HS[19] & 0x0F"]
DynamicTruncate --> ExtractInt["Extract 31-bit Integer from HS[Offset ... Offset+3]"]
ExtractInt --> Modulo["5. Modulo 1,000,000 = 6-Digit Verification Code"]
Modulo --> FinalCode["Display Token: e.g. 524109 (Valid for remaining window)"]
Stage 1: The Time-Step Counter ($C$)
Standard TOTP divides the current Unix epoch timestamp ($T$, measured in seconds) into discrete 30-second time intervals ($T_X$):
$$C = \left\lfloor \frac{T - T_0}{T_X} \right\rfloor$$
Where:
- $T$: Current Unix epoch timestamp
- $T_0$: Epoch start offset (standardized to $0$, representing 1970-01-01 00:00:00 UTC)
- $T_X$: Time-step interval window (standardized to 30 seconds)
The resulting integer $C$ is serialized as an 8-byte (64-bit) big-endian binary buffer.
Stage 2: The HMAC Cryptographic Digest ($HS$)
The client computes a keyed-hash message authentication code using the secret key $K$ and counter $C$:
$$HS = \text{HMAC-SHA-1}(K, C)$$
(While RFC 6238 supports SHA-256 and SHA-512, HMAC-SHA-1 remains the universal default implemented by Google and Microsoft Authenticator).
Stage 3: Dynamic Truncation (Extracting the 31-Bit Binary Code)
The HMAC-SHA-1 output produces a 20-byte array ($HS[0] \dots HS[19]$). To extract a predictable integer without introducing mathematical bias:
- Inspect the lower 4 bits of the final byte ($HS[19]$) to obtain an offset between $0$ and $15$: $$\text{Offset} = HS[19] \ & \ \texttt{0x0F}$$
- Extract four contiguous bytes starting at the offset index ($HS[\text{Offset}] \dots HS[\text{Offset}+3]$).
- Mask the most significant bit with
0x7Fto avoid negative signed integers, creating a 31-bit unsigned integer: $$\text{Binary Code} = ((HS[\text{Offset}] \ & \ \texttt{0x7F}) \ll 24) \mid ((HS[\text{Offset}+1] \ & \ \texttt{0xFF}) \ll 16) \mid ((HS[\text{Offset}+2] \ & \ \texttt{0xFF}) \ll 8) \mid (HS[\text{Offset}+3] \ & \ \texttt{0xFF})$$
Stage 4: Modular Reduction (6-Digit Code)
The 31-bit binary code is modulo-reduced to the desired digit length $d$ (typically $d = 6$):
$$\text{TOTP Code} = \text{Binary Code} \pmod{10^d}$$
The resulting integer is padded with leading zeros to guarantee exactly 6 digits (e.g. 042109).
Anatomy of the otpauth:// URI Protocol
When onboarding a user into 2FA, websites display a QR code containing an otpauth:// URI:
otpauth://totp/AffiChain:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=AffiChain&algorithm=SHA1&digits=6&period=30
| URI Parameter | Standard Setting | Protocol Role & Functionality |
|---|---|---|
Type (totp vs hotp) | totp | Declares whether the token is time-based (totp) or event-counter-based (hotp). |
Label (Issuer:Account) | Provider:user | Human-readable account identifier displayed in the mobile authenticator UI. |
secret | Base32 String | The unencrypted master shared secret key (RFC 4648 alphabet: A-Z, 2-7). |
issuer | String | The organization or platform issuing the token (e.g., GitHub, Google, AffiChain). |
algorithm | SHA1 | Hash function used for HMAC (SHA1, SHA256, or SHA512). |
digits | 6 | Length of the generated code (typically 6; enterprise environments occasionally use 8). |
period | 30 | The refresh duration window in seconds (default is 30s; AWS GovCloud uses 60s). |
Two-Factor Authentication Mechanisms Comparison Matrix
| 2FA Technology | Physical Delivery Channel | Phishing Resistance | SIM-Swap Resilience | Internet Required? | User Friction |
|---|---|---|---|---|---|
| SMS One-Time Codes | Cellular SMS Network | Zero (Trivially phished) | Zero (High SIM-swap risk) | Cellular only | Low |
| Email Verification Codes | SMTP Email Inbox | Low (Credential stuffing) | Moderate (Vulnerable to email hack) | Active internet | Moderate |
| TOTP (RFC 6238) | Local Smartphone App | Moderate (Vulnerable to AiTM) | 100% Immune to SIM swap | Zero (Works completely offline) | Low |
| Push Notifications (Duo) | Encrypted Push App | Moderate (Fatigue attacks) | High | Active internet | Minimal (1 tap) |
| FIDO2 / WebAuthn (YubiKey) | Hardware USB/NFC Key | 100% Cryptographically Immune | 100% Immune | Local USB/NFC | Minimal (Physical touch) |
Practical Implementation Examples
Python: Pure Standard Library RFC 6238 Engine
The following production script implements the complete TOTP pipeline using Python's built-in hmac, hashlib, struct, time, and base64 modules without third-party dependencies:
import hmac
import hashlib
import time
import struct
import base64
def generate_totp_code(base32_secret: str, time_step: int = 30, digits: int = 6) -> dict:
# 1. Normalize Base32 secret (pad with '=' if missing)
clean_secret = base32_secret.strip().replace(' ', '').upper()
missing_padding = len(clean_secret) % 8
if missing_padding:
clean_secret += '=' * (8 - missing_padding)
secret_bytes = base64.b32decode(clean_secret)
# 2. Compute 8-byte big-endian time-step counter
current_time = int(time.time())
counter = current_time // time_step
counter_bytes = struct.pack(">Q", counter)
# 3. Calculate HMAC-SHA-1 digest
hmac_digest = hmac.new(secret_bytes, counter_bytes, hashlib.sha1).digest()
# 4. Dynamic Truncation
offset = hmac_digest[-1] & 0x0F
binary_code = struct.unpack(">I", hmac_digest[offset:offset + 4])[0] & 0x7FFFFFFF
# 5. Modulo reduction to target digits
code = binary_code % (10 ** digits)
formatted_code = str(code).zfill(digits)
# Calculate remaining seconds in current window
seconds_remaining = time_step - (current_time % time_step)
return {
"totp_code": formatted_code,
"seconds_remaining": seconds_remaining,
"unix_timestamp": current_time,
"counter": counter
}
# Example: RFC 6238 Appendix B standard test vector ("JBSWY3DPEHPK3PXP")
token_data = generate_totp_code("JBSWY3DPEHPK3PXP")
print(f"Generated TOTP Code: {token_data['totp_code']}")
print(f"Valid for next: {token_data['seconds_remaining']} seconds")
TypeScript / JavaScript Web Crypto Implementation
export async function computeBrowserTotp(base32Secret: string, stepSeconds: number = 30): Promise<string> {
// Decode Base32
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
let bits = '';
for (const char of base32Secret.toUpperCase().replace(/=/g, '')) {
const val = alphabet.indexOf(char);
if (val === -1) continue;
bits += val.toString(2).padStart(5, '0');
}
const keyBytes = new Uint8Array(Math.floor(bits.length / 8));
for (let i = 0; i < keyBytes.length; i++) {
keyBytes[i] = parseInt(bits.slice(i * 8, (i + 1) * 8), 2);
}
// Calculate Counter
const epoch = Math.floor(Date.now() / 1000);
const counter = Math.floor(epoch / stepSeconds);
const counterBuffer = new ArrayBuffer(8);
const counterView = new DataView(counterBuffer);
counterView.setBigUint64(0, BigInt(counter), false); // Big-endian
// Web Crypto HMAC-SHA1
const cryptoKey = await window.crypto.subtle.importKey(
'raw',
keyBytes,
{ name: 'HMAC', hash: 'SHA-1' },
false,
['sign']
);
const signature = await window.crypto.subtle.sign('HMAC', cryptoKey, counterBuffer);
const hmacBytes = new Uint8Array(signature);
// Dynamic Truncation
const offset = hmacBytes[hmacBytes.length - 1] & 0x0f;
const binary =
((hmacBytes[offset] & 0x7f) << 24) |
((hmacBytes[offset + 1] & 0xff) << 16) |
((hmacBytes[offset + 2] & 0xff) << 8) |
(hmacBytes[offset + 3] & 0xff);
const otp = (binary % 1000000).toString().padStart(6, '0');
return otp;
}
Critical Edge Cases & Common Security Traps
1. Clock Drift & The Grace Window Requirement
Because TOTP relies on synchronized solar time, server clocks that drift by more than 15 seconds will reject valid client tokens. To provide robust real-world usability without sacrificing security, production authentication backends must evaluate a grace window of $\pm 1$ time-step:
# Evaluates counter - 1, counter, and counter + 1 (±30s window)
valid = any(verify_code(secret, c) for c in [counter - 1, counter, counter + 1])
Server infrastructure must synchronize its clock continuously using the Network Time Protocol (NTP).
2. Token Replay Attacks
If a user submits a valid 6-digit code at second 5 of a 30-second window, an eavesdropper could intercept the code and re-submit it during the remaining 25 seconds. Authentication servers must maintain a temporary distributed cache (Redis / Memcached) storing the tuple (user_id, counter). If an incoming token matches an already-consumed counter, the authentication attempt is immediately rejected.
3. Adversary-in-the-Middle (AiTM) Reverse Proxy Phishing
While TOTP is completely immune to SIM-swap attacks, it is not phish-proof. Threat actors deploy reverse-proxy phishing kits (such as Evilginx) that proxy real-time login sessions. When the victim enters their 6-digit TOTP code into the attacker's phishing site, the proxy immediately submits the code to the real service, captures the authenticated session cookie, and hijacks the account. Organizations seeking absolute phishing resistance must deploy FIDO2 / WebAuthn hardware security keys, which cryptographically bind authentication to the browser's origin domain.