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
Development Team
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
| Factor | Meaning | Examples |
|---|---|---|
| Knowledge | Something you know | Password, PIN |
| Possession | Something you have | Phone, hardware key |
| Inherence | Something you are | Fingerprint, face |
2FA combines two of these factors.
Password (knowledge) + TOTP app (possession) = 2FA
PIN (knowledge) + Fingerprint (inherence) = 2FA
Why It's Necessary
| Attack Type | Password Only | With 2FA |
|---|---|---|
| Phishing | Breached | Delayed or blocked |
| Brute force | Potentially breached | Blocked |
| DB leak | Breached | Blocked |
| Shoulder surfing | Breached | Blocked |
Comparing 2FA Types
1. SMS Authentication
Login attempt → Receive 6-digit code on phone → Enter code
| Pros | Cons |
|---|---|
| No additional app needed | Vulnerable to SIM swapping |
| Users are familiar | Vulnerable to phishing |
| Quick to implement | Requires 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
| Pros | Cons |
|---|---|
| Works offline | Requires app installation |
| Immune to SIM swapping | Risk of losing recovery keys |
| Free | Problems if device is lost |
Security Rating: 4/5 (High)
3. Hardware Security Keys
Physical authentication via USB or NFC
Examples: YubiKey, Google Titan Key
| Pros | Cons |
|---|---|
| Complete phishing protection | Cost ($30-70) |
| Strongest security | Risk of physical loss |
| Easy to use | Not 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
| Pros | Cons |
|---|---|
| Convenient | Requires internet |
| Phishing resistant | App dependent |
Security Rating: 4/5 (High)
How TOTP Works
Concept
TOTP = HMAC-SHA1(secret key, time) → 6-digit number
- Server and app share a secret key
- Current time is divided into 30-second intervals
- Hash is generated from secret key + time
- 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 Type | Security | Convenience | Recommendation |
|---|---|---|---|
| SMS | 2/5 | 5/5 | Last resort |
| TOTP App | 4/5 | 4/5 | Generally recommended |
| Hardware Key | 5/5 | 3/5 | High security |
| App Push | 4/5 | 5/5 | Enterprise use |
Use at least TOTP. Passwords alone are not enough.
Related Tools
| Tool | Purpose |
|---|---|
| TOTP Generator | Test 2FA codes |
| Password Generator | Strong passwords |
| Hash Generator | Hashing tests |
About the Author
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.