What is TOTP and how two-factor authentication works
TOTP definition, HMAC-based OTP, time-step, shared secret, authenticator apps, QR code provisioning, backup codes, MFA vs 2FA
How TOTP Works
TOTP (Time-based One-Time Password) generates a 6-digit code that is valid for 30 seconds. Both your server and the user's authenticator app run the same algorithm using a shared secret and the current Unix timestamp. If the codes match, the user has the secret — proving they have access to the device where it was stored.
The shared secret is generated once during setup and typically encoded as a QR code that the user scans with Google Authenticator, Authy, or any TOTP-compatible app. After setup, you never transmit the secret again.
Why TOTP Beats SMS OTP
SMS codes are vulnerable to SIM-swapping attacks where an attacker convinces a carrier to transfer the victim's phone number. TOTP codes never leave the device and are not transmitted over a carrier network, so SIM swapping is irrelevant. Use TOTP by default; only fall back to SMS if device-based TOTP is genuinely not an option for your users.
Backup Codes
Always provide 8–10 single-use backup codes when a user enables TOTP. If they lose their device, these codes are their only recovery path. Hash and store backup codes the same way you store passwords — if your backup codes table leaks, you do not want plaintext codes.
