Toolypet
Back to Blog
Security

Complete 2FA Guide - TOTP, SMS, Hardware Keys Comparison and Implementation

Types and security levels of two-factor authentication (2FA). Pros and cons of TOTP apps, SMS, and hardware keys with implementation guide for developers.

Toolypet Team

Toolypet Team

Development Team

6 min read

Complete 2FA Guide: What, Why, and How

Once your password is leaked, it's over.

As of 2024, over 10 billion passwords have been leaked. No matter how strong your password is, it's powerless against database breaches.

2FA (Two-Factor Authentication) protects your account even if your password is compromised.


What is 2FA?

2FA (Two-Factor Authentication) is authentication using two factors.

The Three Authentication Factors

FactorMeaningExamples
KnowledgeSomething you knowPassword, PIN
PossessionSomething you havePhone, hardware key
InherenceSomething you areFingerprint, face

2FA combines two of these factors.

Password (knowledge) + TOTP app (possession) = 2FA
PIN (knowledge) + Fingerprint (inherence) = 2FA

Why It's Necessary

Attack TypePassword OnlyWith 2FA
PhishingBreachedDelayed or blocked
Brute forcePotentially breachedBlocked
DB leakBreachedBlocked
Shoulder surfingBreachedBlocked

Comparing 2FA Types

1. SMS Authentication

Login attempt → Receive 6-digit code on phone → Enter code
ProsCons
No additional app neededVulnerable to SIM swapping
Users are familiarVulnerable to phishing
Quick to implementRequires cellular connection

Security Rating: 2/5 (Low)

SMS is vulnerable to SIM swapping attacks. If attackers trick the carrier into cloning your SIM, they can intercept SMS messages.

2. TOTP Apps (Recommended)

Time-based One-Time Password
New code generated every 30 seconds

App examples: Google Authenticator, Authy, 1Password

ProsCons
Works offlineRequires app installation
Immune to SIM swappingRisk of losing recovery keys
FreeProblems if device is lost

Security Rating: 4/5 (High)

3. Hardware Security Keys

Physical authentication via USB or NFC
Examples: YubiKey, Google Titan Key
ProsCons
Complete phishing protectionCost ($30-70)
Strongest securityRisk of physical loss
Easy to useNot supported by all services

Security Rating: 5/5 (Highest)

4. App Push Authentication

Login attempt → Push notification to app → Approve/Deny
Examples: Microsoft Authenticator, Duo
ProsCons
ConvenientRequires internet
Phishing resistantApp dependent

Security Rating: 4/5 (High)


How TOTP Works

Concept

TOTP = HMAC-SHA1(secret key, time) → 6-digit number
  1. Server and app share a secret key
  2. Current time is divided into 30-second intervals
  3. Hash is generated from secret key + time
  4. 6-digit number is extracted from the hash

Since both server and app use the same time and same key, they generate the same code.

What's in the QR Code

otpauth://totp/Service:Account?secret=BASE32SECRET&issuer=Service
otpauth://totp/GitHub:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=GitHub

Scanning the QR code saves this information in the app.


TOTP Implementation for Developers

Node.js Example (otplib)

const { authenticator } = require('otplib');

// 1. Generate secret (during user registration)
const secret = authenticator.generateSecret();
// "JBSWY3DPEHPK3PXP"

// 2. Generate QR code URL
const otpauthUrl = authenticator.keyuri(
  'user@example.com',
  'MyApp',
  secret
);
// Generate image with QR library

// 3. Verify code (during login)
const userToken = "123456";  // User input
const isValid = authenticator.verify({ token: userToken, secret });

if (isValid) {
  console.log("Authentication successful");
} else {
  console.log("Invalid code");
}

Python Example (pyotp)

import pyotp

# 1. Generate secret
secret = pyotp.random_base32()

# 2. QR code URL
totp = pyotp.TOTP(secret)
url = totp.provisioning_uri(name='user@example.com', issuer_name='MyApp')

# 3. Verify code
user_token = "123456"
is_valid = totp.verify(user_token)

Security Considerations

// Allow time drift (30 seconds before and after)
authenticator.options = {
  window: 1  // Allow -30sec to +30sec
};

// Prevent reuse
// Store used codes and block same code reuse
const usedCodes = new Set();

function verifyOnce(token, secret) {
  if (usedCodes.has(token)) return false;

  if (authenticator.verify({ token, secret })) {
    usedCodes.add(token);
    // Delete after 60 seconds (memory management)
    setTimeout(() => usedCodes.delete(token), 60000);
    return true;
  }
  return false;
}

Recovery Code Management

If you lose 2FA, you can't access your account. Always provide recovery codes.

Generation

const crypto = require('crypto');

function generateRecoveryCodes(count = 10) {
  const codes = [];
  for (let i = 0; i < count; i++) {
    // 8-character uppercase + numbers
    const code = crypto.randomBytes(4).toString('hex').toUpperCase();
    codes.push(`${code.slice(0,4)}-${code.slice(4)}`);
  }
  return codes;
}

// ["A3F8-B2C1", "D4E5-F6G7", ...]

Storage

// Hash recovery codes before storing (bcrypt recommended)
const bcrypt = require('bcrypt');

async function storeRecoveryCodes(codes) {
  const hashedCodes = await Promise.all(
    codes.map(code => bcrypt.hash(code, 10))
  );
  // Store hashedCodes in DB
}

// Verify when used
async function useRecoveryCode(inputCode, hashedCodes) {
  for (const hashed of hashedCodes) {
    if (await bcrypt.compare(inputCode, hashed)) {
      // Delete code (one-time use)
      return true;
    }
  }
  return false;
}

User Experience (UX) Tips

1. Encourage 2FA Setup

After first login: "Set up 2FA to secure your account"
Before sensitive actions: "2FA is required for this action"

2. Step-by-Step Guidance

Step 1: Install authenticator app (provide Google Authenticator link)
Step 2: Scan QR code
Step 3: Confirm with 6-digit code
Step 4: Save recovery codes (emphasize!)

3. Emphasize Recovery Codes

Warning: Save these codes in a safe place.
Account recovery will be impossible if lost.

[ Download Codes ] [ Copy Codes ]

FAQ

Q: Should I avoid SMS 2FA entirely?

A: It's weaker than TOTP, but much better than nothing. Use TOTP or hardware keys when possible, but if a service only supports SMS, definitely enable it.

Q: What if I lose my phone with the 2FA app?

A: Log in with a recovery code and reset 2FA. That's why you must keep recovery codes stored separately and safely.

Q: Can I register backup 2FA?

A: Yes, register multiple devices to the same account (if the service supports it), or scan the QR code on multiple devices simultaneously during initial setup.


Summary

2FA TypeSecurityConvenienceRecommendation
SMS2/55/5Last resort
TOTP App4/54/5Generally recommended
Hardware Key5/53/5High security
App Push4/55/5Enterprise use

Use at least TOTP. Passwords alone are not enough.


Related Tools

ToolPurpose
TOTP GeneratorTest 2FA codes
Password GeneratorStrong passwords
Hash GeneratorHashing tests
2FAMFATOTPauthenticationsecuritydevelopment

About the Author

Toolypet Team

Toolypet Team

Development Team

The Toolypet Team creates free, privacy-focused web tools for developers and designers. All tools run entirely in your browser with no data sent to servers.

Web DevelopmentCSS ToolsDeveloper ToolsSEOSecurity