Use TOTP/2FA Code Generator

Enter your data below to use the TOTP/2FA Code Generator

📌 Try these examples:
RESULT

Last updated

TOTP 2FA Code Generator Examples

The TOTP 2FA Code Generator generates Time-based One-Time Passwords for testing and development of two-factor authentication systems. Below are practical examples covering the algorithm, implementation, and testing workflows.

How TOTP Works

// TOTP Algorithm (RFC 6238):
// 1. Get current Unix timestamp
// 2. Divide by time step (30 seconds) → time counter T
// 3. Compute HMAC-SHA1(secret_key, T)
// 4. Extract 6-digit code via dynamic truncation

// Example:
Secret key (Base32): JBSWY3DPEHPK3PXP
Current time:        1710504000 (2024-03-15 14:00:00 UTC)
Time counter T:      1710504000 / 30 = 57016800
HMAC-SHA1:           computed from secret + T
6-digit code:        123456 (example)
Valid for:           30 seconds

Base32 Secret Key Format

// TOTP secrets are Base32-encoded
// Base32 alphabet: A-Z and 2-7 (32 characters total)
// Typical length: 16-32 characters

// Example secret keys:
JBSWY3DPEHPK3PXP          // 16 chars (80 bits)
JBSWY3DPEHPK3PXPJBSWY3DP  // 24 chars (120 bits)
JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP  // 32 chars (160 bits)

// Spaces are ignored (for readability):
JBSW Y3DP EHPK 3PXP  →  JBSWY3DPEHPK3PXP

// Case-insensitive:
jbswy3dpehpk3pxp  →  JBSWY3DPEHPK3PXP

otpauth URI Format (QR Code)

// Format used in QR codes for authenticator app setup:
otpauth://totp/{label}?secret={secret}&issuer={issuer}&algorithm={algo}&digits={digits}&period={period}

// Example:
otpauth://totp/alice@example.com?secret=JBSWY3DPEHPK3PXP&issuer=MyApp&algorithm=SHA1&digits=6&period=30

// Parameters:
// label:     account identifier (shown in authenticator app)
// secret:    Base32-encoded shared secret
// issuer:    service name (shown in authenticator app)
// algorithm: SHA1 (default), SHA256, SHA512
// digits:    6 (default) or 8
// period:    30 (default) seconds

JavaScript TOTP Implementation

// Using the 'otplib' library (npm install otplib)
import { authenticator } from 'otplib';

const secret = 'JBSWY3DPEHPK3PXP';

// Generate current TOTP code
const token = authenticator.generate(secret);
console.log('Current code:', token);  // e.g., "123456"

// Verify a code
const isValid = authenticator.verify({ token: '123456', secret });
console.log('Valid:', isValid);  // true or false

// Get time remaining (seconds until code expires)
const timeRemaining = authenticator.timeRemaining();
console.log('Expires in:', timeRemaining, 'seconds');

// Generate QR code URI
const otpauthUrl = authenticator.keyuri('alice@example.com', 'MyApp', secret);
console.log('QR URI:', otpauthUrl);

Python TOTP Implementation

// Using pyotp (pip install pyotp)
import pyotp
import time

secret = 'JBSWY3DPEHPK3PXP'
totp = pyotp.TOTP(secret)

# Generate current code
code = totp.now()
print(f'Current code: {code}')  # e.g., "123456"

# Verify a code
is_valid = totp.verify('123456')
print(f'Valid: {is_valid}')

# Time remaining
remaining = 30 - (int(time.time()) % 30)
print(f'Expires in: {remaining} seconds')

# Generate provisioning URI (for QR code)
uri = totp.provisioning_uri(name='alice@example.com', issuer_name='MyApp')
print(f'QR URI: {uri}')

# Generate QR code image
import qrcode
img = qrcode.make(uri)
img.save('totp_qr.png')

Server-Side Verification (Node.js)

// Express.js TOTP verification endpoint
import { authenticator } from 'otplib';

app.post('/api/auth/verify-2fa', async (req, res) => {
  const { userId, totpCode } = req.body;

  // Retrieve user's TOTP secret from database
  const user = await db.users.findById(userId);
  if (!user || !user.totpSecret) {
    return res.status(400).json({ error: '2FA not configured' });
  }

  // Verify the code (allows ±1 time step for clock drift)
  authenticator.options = { window: 1 };
  const isValid = authenticator.verify({
    token: totpCode,
    secret: user.totpSecret
  });

  if (!isValid) {
    return res.status(401).json({ error: 'Invalid 2FA code' });
  }

  // Issue session token
  const sessionToken = generateSessionToken(userId);
  res.json({ success: true, token: sessionToken });
});

TOTP Setup Flow (Enrollment)

// Step 1: Generate a new secret for the user
const secret = authenticator.generateSecret();  // e.g., "JBSWY3DPEHPK3PXP"

// Step 2: Store secret in database (encrypted)
await db.users.update(userId, {
  totpSecret: encrypt(secret),
  totpEnabled: false  // not yet verified
});

// Step 3: Generate QR code URI
const otpauthUrl = authenticator.keyuri(user.email, 'MyApp', secret);

// Step 4: Display QR code to user (use qrcode library)
// User scans with Google Authenticator, Authy, etc.

// Step 5: User enters first code to verify setup
app.post('/api/auth/setup-2fa/verify', async (req, res) => {
  const { code } = req.body;
  const isValid = authenticator.verify({ token: code, secret });
  if (isValid) {
    await db.users.update(userId, { totpEnabled: true });
    res.json({ success: true });
  }
});

Testing TOTP with the Generator

// Use the TOTP generator to test your implementation:

// 1. Enter your test secret key:
Secret: JBSWY3DPEHPK3PXP

// 2. Generator shows current code:
Current code: 123456
Time remaining: 18 seconds

// 3. Use the code to test your server endpoint:
POST /api/auth/verify-2fa
{ "userId": "test-user", "totpCode": "123456" }

// 4. Verify your server accepts the code
// 5. Wait for code to expire and verify rejection

// Common issues to test:
// - Code accepted within valid window
// - Expired code rejected
// - Wrong code rejected
// - Clock drift tolerance (±30 seconds)
// - Replay attack prevention (same code used twice)

8-Digit TOTP (Enhanced Security)

// Some systems use 8-digit codes for additional security
// Configure in otplib:
authenticator.options = { digits: 8 };
const code = authenticator.generate(secret);
// Returns 8-digit code: "12345678"

// otpauth URI for 8-digit TOTP:
otpauth://totp/alice@example.com?secret=JBSWY3DPEHPK3PXP&digits=8&period=30

Common Use Cases

Enter your Base32 secret key in the TOTP generator to see the current code, time remaining, and QR code for authenticator app setup.

Frequently Asked Questions

Simply enter your data, click the process button, and get instant results. All processing happens in your browser for maximum privacy and security.

Yes! TOTP/2FA Code Generator is completely free to use with no registration required. All processing is done client-side in your browser.

Absolutely! All processing happens locally in your browser. Your data never leaves your device, ensuring complete privacy and security.