Skip to content

Two-Factor Authentication and TOTP: How Codes Are Generated

10 September 20251 min read
SCIENCE & TECHNOLOGYTwo-FactorAuthentication andTOTP: How Codes AreGenerated10 September 2025safalsetu.com

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

  1. At setup the service gives the app a secret key, often by QR code; both store it.
  2. Time is cut into 30-second slices, each with a counter.
  3. Key plus counter go through HMAC-SHA-256.
  4. 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

MethodBasis
HOTPCounter instead of time
Push-based 2FAApproval notifications
Hardware tokens (YubiKey)Device generates codes itself

Exam angle

  • TOTP interval: 30 seconds.

Test yourself

1. How often does a TOTP code change?

TOTP uses 30-second time intervals.

2. What does the H in HMAC stand for?

HMAC means Hash-based Message Authentication Code.

3. Which authentication method uses a counter instead of the clock?

Counter-based OTP is HOTP.