Two-Factor Authentication and TOTP: How Codes Are Generated
Why in the news
With cyber threats rising, a password alone is weak, so many services add Two-Factor Authentication using apps such as Google Authenticator that produce TOTPs.
Key facts
- OTP: a short numeric code usable once and valid for seconds.
- TOTP: an OTP refreshing every 30 seconds, built on an open standard so apps and services interoperate.
- The final code has 6 digits (000000 to 999999).
How TOTP works
- At setup the service gives the app a secret key, often by QR code; both store it.
- Time is cut into 30-second slices, each with a counter.
- Key plus counter go through HMAC-SHA-256.
- Dynamic truncation extracts part of the output, reduced to 6 digits.
Phone and server share the key and the time slice, so they compute identical codes.
About HMAC
- Hash-based Message Authentication Code: mixes a secret key with a message through a hash such as SHA-256, using XOR.
- Gives authenticity (only the key holder makes valid codes) and integrity (tampering is detectable).
Why it is secure
- Key stored only on device and server; SHA-256 resists reversal.
- Codes lapse every 30 seconds and come from a huge key space.
Alternatives
| Method | Basis |
|---|---|
| HOTP | Counter instead of time |
| Push-based 2FA | Approval notifications |
| Hardware tokens (YubiKey) | Device generates codes itself |
Exam angle
- TOTP interval: 30 seconds.