Passwords akele dead hain। Data breaches har saal billions of credentials expose karte hain, aur credential stuffing attacks sirf isliye succeed karte hain kyunki log passwords reuse karte hain। Time-based One-Time Passwords (TOTP) ek second factor generate karte hain jo har 30 seconds mein change hota hai — mathematically derived from a shared secret aur current time. Attacker aapka password chura bhi le toh bhi 6-digit code ke bina login nahi kar sakta।
Is guide mein: HOTP aur TOTP ka mathematical foundation (HMAC-SHA1, base32, 30-second time window), sab 2FA methods ka comparison, major platforms pe setup, device loss recovery, real attack vectors (phishing, real-time relay) aur best practices — developers aur security-conscious users dono ke liye।
TOTP Codes Generate aur Test Karo
Secure TOTP secret generate karo, QR code scan karo aur real-time 6-digit codes verify karo। SHA-1, SHA-256, SHA-512 test karo। Free, server pe koi storage nahi, sab browser mein process।
TOTP kya hai? Time-Based One-Time Passwords kaise Kaam Karte Hain
TOTP ka full form hai Time-based One-Time Password। Yeh RFC 6238 (2011) mein defined hai, HOTP (RFC 4226) ka extension। Core idea: shared secret key aur current time use karke ek short numeric code generate karo, aur dono sides (server aur user ka authenticator app) independently same code produce karein — bina communicate kiye।
TOTP Algorithm Step by Step
import hmac, hashlib, struct, time, base64
def generate_totp(secret_base32: str, digits: int = 6, period: int = 30) -> str:
# Step 1: Base32 secret decode karo
secret_bytes = base64.b32decode(secret_base32.upper())
# Step 2: T calculate karo (time counter)
T = int(time.time()) // period
# Example: 1710835200 / 30 = 57027840
# Step 3: T ko 8-byte big-endian mein pack karo
T_bytes = struct.pack('>Q', T)
# Step 4: HMAC-SHA1 compute karo
hmac_result = hmac.new(secret_bytes, T_bytes, hashlib.sha1).digest()
# Result: 20 bytes
# Step 5: Dynamic Truncation
offset = hmac_result[-1] & 0x0F
code_int = struct.unpack('>I', hmac_result[offset:offset + 4])[0] & 0x7FFFFFFF
# Step 6: Modulo reduction
otp = code_int % (10 ** digits)
return str(otp).zfill(digits) # e.g., "847291"
Time Window aur Validity
Current UNIX time: 1,710,835,246
T = floor(1,710,835,246 / 30) = 57,027,841
Ye code valid hai: 1,710,835,210 se 1,710,835,239 tak (exactly 30 seconds)
Servers T-1 (previous window) aur T+1 (next window) bhi accept karte hain:
- Clock skew handle karne ke liye
- User ke typing time ke liye
Total effective validity: 60-90 seconds.
QR Code aur otpauth URI
Scan karne wala QR code ek otpauth:// URI contain karta hai:
otpauth://totp/MyApp:user@example.com?
secret=JBSWY3DPEHPK3PXP&
issuer=MyApp&
algorithm=SHA1&
digits=6&
period=30
Fields:
- secret: Base32-encoded shared secret (16-32 characters)
- issuer: Service name (app mein dikhta hai)
- digits: 6 (standard) ya 8 (higher security)
- period: 30 seconds (default)
TOTP vs SMS OTP vs Hardware Keys: Security Comparison
| Method | Phishing Resistant | SIM Swap Resistant | Works Offline | Security Level |
|---|---|---|---|---|
| SMS OTP | Nahi | Nahi (major weakness) | Cellular signal chahiye | Weak |
| TOTP (RFC 6238) | Partial (relay possible) | Haan | Haan (offline) | Good |
| FIDO2/WebAuthn Passkey | Haan (domain-bound) | Haan | Haan | Excellent |
| Hardware Key (YubiKey) | Haan | Haan | Haan | Excellent |
| Push Notification | Partial (MFA fatigue) | Haan | Internet chahiye | Good |
SMS 2FA Kyun Critically Weak Hai
SIM Swap Attack:
1. Attacker aapke carrier ko social engineering se call karta hai
("Mera phone kho gaya, number naye SIM pe transfer karo")
2. Carrier aapka number attacker ke SIM pe transfer kar deta hai
3. Attacker password reset request karta hai → SMS unke phone pe aata hai
4. Account fully compromised
High-profile victims:
- Jack Dorsey (Twitter CEO) — 2019
- Multiple crypto exchange CEOs — 2021-2023
SS7 vulnerability: Nation-state actors SMS messages in-transit intercept kar sakte hain।
HOTP/TOTP Standard: RFC 6238 Jargon-Free Explanation
HOTP Foundation (RFC 4226)
HOTP mein time ke bajaye counter use hota hai:
def generate_hotp(secret: bytes, counter: int, digits: int = 6) -> str:
counter_bytes = struct.pack('>Q', counter)
hmac_result = hmac.new(secret, counter_bytes, hashlib.sha1).digest()
offset = hmac_result[-1] & 0x0F
code = struct.unpack('>I', hmac_result[offset:offset + 4])[0] & 0x7FFFFFFF
return str(code % (10 ** digits)).zfill(digits)
# HOTP problem: counter client aur server ke beech sync rakhna padta hai
# TOTP ne counter ki jagah time use karke yeh problem solve kiya
RFC 6238 Parameters
| Parameter | RFC Default | Common Values |
|---|---|---|
| Hash algorithm | HMAC-SHA1 | SHA1, SHA256, SHA512 |
| Time step | 30 seconds | 30s (universal) |
| Code digits | 6 | 6 (universal), 8 (banks) |
| Secret length | ≥128 bits | 160 bits (Base32: 32 chars) |
Secret Key Generate aur Store Karna
import secrets
import base64
# Cryptographically random 160-bit secret generate karo
secret_bytes = secrets.token_bytes(20) # 20 bytes = 160 bits
secret_b32 = base64.b32encode(secret_bytes).decode('utf-8')
# SECRET KO KABHI PLAINTEXT MEIN DATABASE MEIN MAT STORE KARO
# AES-256-GCM ya KMS use karo (AWS KMS, Google Cloud KMS, HashiCorp Vault)
TOTP 2FA Setup: Major Platforms ke liye Step-by-Step
GitHub pe TOTP Setup
1. Settings → Password and authentication → Two-factor authentication
2. "Enable two-factor authentication" click karo
3. "Authenticator app" select karo
4. QR code scan karo (Aegis/Raivo/Bitwarden se)
5. 6-digit code enter karo verify karne ke liye
6. CRITICAL: 16 recovery codes download/copy karo
- Har code sirf ek baar use hota hai
- Password manager mein save karo + printed copy
Node.js mein TOTP Implementation
import * as speakeasy from 'speakeasy';
import * as QRCode from 'qrcode';
// 1. Naye user ke liye secret generate karo
async function setupTOTP(userId: string, userEmail: string) {
const secret = speakeasy.generateSecret({
name: `MyApp (${userEmail})`,
issuer: 'MyApp',
length: 20,
});
const qrCode = await QRCode.toDataURL(secret.otpauth_url);
// Database mein ENCRYPTED secret store karo
await db.users.update(userId, {
totpSecretEncrypted: await encryptSecret(secret.base32),
totpEnabled: false,
});
return { secret: secret.base32, qrCode };
}
// 2. Login pe TOTP validate karo
async function validateTOTP(userId: string, token: string) {
const user = await db.users.findById(userId);
const secret = await decryptSecret(user.totpSecretEncrypted);
return speakeasy.totp.verify({
secret,
encoding: 'base32',
token,
window: 1, // T-1 aur T+1 accept karo
});
}
Authenticator Apps Comparison
| App | Platform | Open Source | Cloud Backup | Export |
|---|---|---|---|---|
| Aegis | Android only | Haan (GPL-3) | Self-managed encrypted | Haan |
| Raivo OTP | iOS only | Haan (MIT) | iCloud (E2E encrypted) | Haan |
| Bitwarden | All platforms | Haan (AGPL) | Bitwarden cloud | Haan |
| Authy | All platforms | Nahi | Authy cloud | Nahi (lock-in!) |
| Google Auth | iOS, Android | Nahi | Google account | Limited |
TOTP Device Kho Gaye Toh kya Karein: Recovery Planning
Tier 1: Backup Codes (Zaroori Hai)
Backup codes store karne ke best practices:
✓ Password manager mein secure note mein
✓ Print karke physical safe mein
✓ Multiple geographic locations pe
Kabhi mat karo:
✗ Same device pe screenshot
✗ Email se bhejo khud ko
✗ Unencrypted notes mein
✗ Computer pe plaintext file mein
Backup code use karne ke baad:
1. Code se login karo
2. TOTP disable karo
3. Naye device pe re-enroll karo
4. Naye backup codes generate aur save karo
Tier 2: Cloud Backup Wale Apps
Aegis (Android):
- Settings → Backups → Enable automatic backups
- Password se encrypt hota hai
- Restore: Install Aegis → Restore from backup → Password enter karo
Raivo (iOS):
- iCloud mein end-to-end encrypt hota hai
- Naye iOS device pe auto-restore
WARNING: Google Authenticator ka cloud sync (2023 mein add hua)
end-to-end ENCRYPT NAHI karta — Google technically access kar sakta hai।
Aegis ya Raivo use karo E2E encryption ke liye।
Tier 3: Multi-Device Enrollment
Critical accounts ke liye: setup ke waqt ek QR code do devices se scan karo
Device 1: Primary phone (Aegis/Raivo)
Device 2: Tablet, spare phone ya Bitwarden 2FA
Device 3: Desktop app (Bitwarden, 1Password)
Dono same code generate karenge (same secret + same time)।
Device 1 kho jaaye toh Device 2 kaam karega।
TOTP ke Security Risks: Phishing, SIM Swap aur Mitigation
Attack 1: Real-Time Phishing (Sabse Dangerous)
Real-Time TOTP Relay Attack:
[User] → [Attacker ka fake site] → [Real site]
1. User fake login page visit karta hai (g00gle.com/login)
2. Username + password enter karta hai
3. Attacker credentials real Google ko relay karta hai
4. Google: "2FA code enter karo"
5. Fake site: "6-digit code enter karo"
6. User TOTP code enter karta hai
7. Attacker code seconds mein real Google pe relay karta hai
8. Attacker full session access paata hai
Ye attack isliye work karta hai kyunki:
- TOTP codes ~90 seconds valid hote hain
- Relay real-time mein automated hoti hai
- Domain binding nahi hai TOTP mein
Real-world tools: Evilginx2, Modlishka — open-source TOTP bypass frameworks
Passkeys TOTP Se Zyada Secure Kyun Hain
FIDO2/WebAuthn domain binding:
Passkey authentication mein:
- Browser exact origin (e.g., "https://accounts.google.com") sign karta hai
- Passkey SIRF US SPECIFIC DOMAIN ke liye create hua tha
- Fake site (g00gle.com) ka DIFFERENT domain hai
- Passkey different domain ke liye REFUSE kar deta hai
- Attack impossible — chahe fake site kitna bhi convincing ho
TOTP mein domain binding nahi:
- 6-digit code kisi bhi site pe kaam karta hai
- Isliye relay attack work karta hai
MFA Fatigue Attack
Push notification 2FA pe attack:
1. Attacker ke paas credentials hain (data breach se)
2. Attacker baar baar login attempt karta hai → push notifications trigger
3. Target phone pe "Allow login?" notifications flood hoti hain
4. Target confused ya irritated hokar "Allow" tap kar deta hai
5. Account compromised
Solution: "Number matching" enable karo — push mein number show karo
jo user ko login page pe match karna hoga।
Real example: Uber 2022 breach isi technique se hua।
TOTP Best Practices: Backup Codes, Multiple Devices aur App Recommendations
Individual Users ke liye Checklist
TOTP enable karne se pehle:
□ Authenticator app choose karo (Android: Aegis, iOS: Raivo, Cross-platform: Bitwarden)
□ Backup codes kahan store karoge decide karo
□ Device loss plan ready rakho
Setup ke waqt:
□ Primary device pe QR scan karo
□ Optional: secondary device pe bhi same QR scan karo
□ Code verify karo setup finalize karne se pehle
□ Sab backup codes turant save karo
□ Password manager mein + printed copy safe mein
Ongoing:
□ Backup codes update karo (ek use hone ke baad regenerate)
□ Saal mein ek baar recovery test karo
□ TOTP code kabhi SMS/email/phone call se share mat karo — fraud hai
Developers ke liye Implementation Best Practices
// 1. Rate limiting — brute force prevent karo
const rateLimiter = rateLimit({
windowMs: 30 * 1000, // 30 second window
max: 3, // 3 attempts per window
skipSuccessfulRequests: true,
});
// 2. Token reuse prevention — ek code ek baar hi use ho
async function markTokenUsed(userId: string, token: string, T: number) {
const key = `totp:used:${userId}:${T}:${token}`;
const existed = await redis.set(key, '1', 'EX', 90, 'NX');
if (!existed) throw new Error('Token already used');
}
// 3. Timing-safe comparison — timing attacks prevent karo
import { timingSafeEqual } from 'crypto';
function safeCompare(a: string, b: string): boolean {
const bufA = Buffer.from(a, 'utf8');
const bufB = Buffer.from(b, 'utf8');
if (bufA.length !== bufB.length) return false;
return timingSafeEqual(bufA, bufB);
}
// 4. Backup codes — hash karke store karo
async function hashBackupCode(code: string): Promise {
const salt = randomBytes(16);
const derived = await scryptAsync(code, salt, 64) as Buffer;
return salt.toString('hex') + ':' + derived.toString('hex');
}
Organization Level TOTP Policy
Developer teams ke liye recommended policy:
□ Production access wale sab accounts pe TOTP mandatorate karo
(AWS, GitHub, GCP, Azure, Cloudflare)
□ SMS 2FA kabhi production system access ke liye allow mat karo
□ Hardware keys (YubiKey) use karo:
- Domain registrar accounts
- DNS provider accounts
- Certificate authority accounts
□ Team password manager mein backup codes store karo
(1Password Teams, Bitwarden Teams)
□ Quarterly audit:
- Kaun 2FA mein enrolled hai?
- Koi SMS 2FA use kar raha hai?
- Shared accounts bina 2FA ke?
How to Use the Tool (Step by Step)
- 1
TOTP secret generate ya enter karo
TOTP 2FA Generator se new random Base32 secret create karo, ya existing secret enter karo test karne ke liye। Tool default mein cryptographically secure 160-bit secret generate karta hai।
- 2
QR code authenticator app se scan karo
Aegis, Raivo, Bitwarden ya Google Authenticator se QR code scan karo। App secret store karta hai aur 6-digit codes generate karna start karta hai।
- 3
Current TOTP code verify karo
Tool current 6-digit TOTP code aur countdown timer show karta hai। Verify karo ki yeh aapke authenticator app ke saath match karta hai।
- 4
Time window note karo
Validity window check karo — code 30 seconds valid hota hai। Servers T-1 aur T+1 bhi accept karte hain, effectively 90 seconds validity।
- 5
Different algorithms test karo
Advanced users SHA-256 ya SHA-512, ya 8-digit codes test kar sakte hain — kuch banking applications mein use hote hain। Most services default SHA-1/6-digit use karte hain।
- 6
Backup codes save karo
Real accounts pe TOTP enable karte waqt, service ke backup codes turant save karo। Password manager mein store karo aur optionally print karo।
Frequently Asked Questions
TOTP bina communicate kiye dono sides pe same code kaise generate karta hai?+−
Dono sides ek hi shared secret key share karte hain (setup ke waqt QR code se exchange hua) aur current time jaante hain। TOTP HMAC-SHA1(secret, floor(current_time / 30)) apply karta hai ek deterministic code produce karne ke liye। Same inputs → same output — koi communication needed nahi। Yeh hai TOTP ka cryptographic magic: shared secret + synchronized clocks = synchronized codes।
Kya TOTP 2026 mein safe hai? Passkeys use karni chahiye?+−
TOTP password-only login se significantly zyada secure hai aur SMS OTP se bahut zyada secure। Lekin TOTP phishing-resistant NAHI hai — real-time relay attacks TOTP codes passwords ke saath chura sakte hain। Passkeys (FIDO2/WebAuthn) phishing-resistant hain kyunki cryptographically domain-bound hain। 2026 mein: passkeys jahan available hain (Google, GitHub, Apple, Microsoft) use karo; baaki jagah TOTP। SMS OTP sensitive accounts ke liye kabhi mat use karo।
Agar phone ka clock galat ho toh kya hoga?+−
Agar phone ka clock significantly galat hai, TOTP codes server ke codes se match nahi karenge। Most servers T-1 aur T+1 (±30 seconds) accept karte hain minor clock skew ke liye। 90 seconds se zyada off clock authentication failures cause karega। Fix: device pe automatic time sync (NTP) enable karo। Android mein: Settings → General management → Date and time → Automatic date and time ON।
TOTP codes brute-force ho sakte hain?+−
Theoretically, sirf 10 lakh (1,000,000) possible 6-digit codes hain। Lekin servers rate limiting enforce karte hain — typically 3 attempts per 30-second window। Is rate pe average code brute-force karne mein hazaron saal lagenge। Plus account lockout after repeated failures। Proper server-side rate limiting ke saath, TOTP brute force practically infeasible hai।
Authy kyun use nahi karni chahiye?+−
Authy ke main drawbacks: (1) Export nahi — TOTP secrets Authy se export nahi kar sakte। App switch karna chahte ho toh sab accounts manually re-enroll karni padti hain। (2) Proprietary closed-source backup। (3) Linux ke liye desktop app nahi। Alternatives: Aegis (Android, open source, fully exportable), Raivo (iOS, open source, iCloud E2E encrypted), Bitwarden (cross-platform, open source, full export/import)।
TOTP Codes Generate aur Test Karo
Secure TOTP secret generate karo, QR code scan karo aur real-time 6-digit codes verify karo। SHA-1, SHA-256, SHA-512 test karo। Free, server pe koi storage nahi, sab browser mein process।
TOTP 2FA Generator KholeinRelated Guides
मज़बूत पासवर्ड कैसे बनाएं — Password Security Guide 2026
UPI fraud, SIM swap और hacking से बचें — India-specific password security guide।
Hash Generator — MD5, SHA-256 Online Guide Hindi (2026)
MD5, SHA-256, SHA-512 hashes online generate करें — hashing समझें, file verify करें।
Base64 Encode & Decode — क्या है, कैसे काम करता है? (Developer Guide)
Base64 encoding की पूरी जानकारी — use cases, online decoder, और common pitfalls