Skip to main content

Command Palette

Search for a command to run...

How do MFA Codes work??

Updated
9 min read
How do MFA Codes work??
M
Software Engineer focused on building scalable web applications using Python, React and AWS.

Introduction

We've all used MFA codes in our daily routines, those six-digit numbers that change every 30 seconds on our authenticator apps. For me, it was a daily ritual, logging into my client VDI for work, entering credentials, then typing the code from my Ping ID app.

One day, I forgot to turn on WiFi before logging in. The code still worked. Another time, I deliberately waited until the code expired and tried the old one - surprisingly, it was still accepted. These moments sparked my curiosity, how do these codes work without internet connectivity? Why do they have a grace period?

What I discovered was elegantly simple yet cryptographically robust. TOTP (Time-based One-Time Password) doesn't rely on complex infrastructure or constant server communication. Instead, it uses shared secrets and synchronized time - a brilliant demonstration that effective security solutions don't need to be complicated.

This experience reinforced an important engineering principle

"The best solutions are often those that elegantly combine simple, well-understood components rather than adding layers of complexity."

It's not a real solution....

In this blog, I'll break down how TOTP works under the hood, explain the mathematics (in accessible terms), and explore why this "simple" approach has become the industry standard for MFA.

How TOTP Works: The Core Concept

The Problem: Single Point of Failure

Traditional authentication relies solely on passwords - something you know. While this works, it has a critical vulnerability. If an attacker obtains your password through phishing, data breaches, or keyloggers, they can impersonate you completely. The password becomes a single point of failure.

Multi-Factor Authentication (MFA) solves this by requiring two independent factors:

  1. Something you know - Your password

  2. Something you have - Your phone/device generating MFA codes

Even if your password is compromised, the attacker still needs physical access to your authenticator device. The constantly changing codes add a time-sensitive barrier that makes stolen credentials nearly useless.

The TOTP Solution: Synchronized Secrets

Here's where it gets interesting. You might think MFA codes are random, but they're not - they're deterministic. Both your device and the server generate the exact same code at the exact same time, independently, without communicating.

How? They use the same two inputs:

  1. A shared secret - Established during initial setup

  2. Current time - Universal and freely available

The Setup Phase

When you first register your MFA device:

  1. The server generates a random secret key (e.g., a long string like JBSWY3DPEHPK3PXP)

  2. This secret is encoded into a QR code and displayed

  3. Your authenticator app scans and stores this secret locally

  4. Both the server and your device now possess the same secret

This is the only time information is exchanged. From this point forward, both sides independently generate identical codes.

Code Generation Process

Let's walk through a concrete example:

Setup:

  • Shared secret: JBSWY3DPEHPK3PXP

  • Time step: 30 seconds

  • Current Unix timestamp: 1708675200

On Your Device:

1. Time Counter = floor(1708675200 / 30) = 56955840
2. HMAC-SHA1(Secret: "JBSWY3DPEHPK3PXP", Counter: 56955840) 
   - produces a 20-byte hash
3. Dynamic truncation - extracts 4 bytes from the hash
4. Convert to integer and take modulo 1,000,000
5. Result: 482019 (your 6-digit code)

On The Server (simultaneously):

1. Time Counter = floor(1708675200 / 30) = 56955840  (Same!)
2. HMAC-SHA1(Secret: "JBSWY3DPEHPK3PXP", Counter: 56955840)
   - produces the same 20-byte hash
3. Same truncation process
4. Same modulo operation
5. Result: 482019 (Same code!)

The Authentication Flow

When you attempt to log in:

  1. You enter your password (first factor)

  2. You open your authenticator app and see: 482019

  3. You enter this code on the login page

  4. The server performs the same calculation using the stored secret for your account and its current system time

  5. Server generates: 482019

  6. Server compares: 482019 == 482019

  7. Authentication successful!

The Time Window Grace Period

Remember when I mentioned that expired codes still worked? That's intentional. Servers typically accept codes from:

  • Current 30-second window

  • Previous 30-second window

  • Next 30-second window

This gives you a ±30 second tolerance to account for clock drift between devices, network latency during login, and the time it takes to type the code.

So if you enter a code from the previous window (482019) while the current window has moved on (generating 847201), the server checks both and accepts the older one.

Why This Works Offline

The brilliance of TOTP is that it requires no network communication after setup. Your phone generates valid codes because it has the secret (stored during QR code scan), it has access to time (device clock), and it follows the same algorithm (HMAC-SHA1 + truncation).

The server does the exact same thing independently. They stay synchronized through mathematics, not communication.

Why TOTP is Creative

Synchronized Chaos

Credits - Veritasium

The genius of TOTP is that it creates synchronized randomness without synchronization. Both client and server use the same inputs (secret + time) but never communicate. It's like two musicians playing the same song in different rooms without hearing each other - they stay in sync by following the same sheet music (the RFC 6238 specification) and the same conductor (Unix time).

Time as a Shared Resource

Using time as a counter is brilliant because:

  • It's universally available (no API needed)

  • It's monotonically increasing (can't go backwards)

  • It's standardized (Unix epoch)

The 30-second window provides the perfect balance, long enough for humans to type the code, short enough to minimize attack windows.

Security Analysis

What Makes TOTP Secure?

1. Secret Key Protection The 160-bit secret provides 2^160 possible combinations - computationally infeasible to brute force. As long as the secret remains secure on both ends, the system is solid.

2. Time-Limited Validity Each code expires in 30 seconds. Even if an attacker intercepts a code, they have a tiny window to use it, and replay attacks are prevented by incrementing counters.

3. Cryptographic Hash Functions HMAC-SHA1 provides:

  • Collision resistance

  • Avalanche effect (small input changes drastically alter output)

  • One-way computation (can't reverse-engineer the secret)

4. Offline Operation No network dependency means:

  • No man-in-the-middle attacks during code generation

  • Works everywhere (planes, basements, foreign countries)

Potential Vulnerabilities

Being honest about limitations

1. Secret Key Compromise If an attacker gets your secret (through malware, device theft, or backup exposure), they can generate valid codes. This is why device security matters.

2. Phishing Attacks TOTP codes are valid for whoever uses them first. Real-time phishing (where attackers immediately use your code) remains a threat. This is why FIDO2 / WebAuthn is gaining traction.

3. SHA-1 Concerns While SHA-1 has known collision vulnerabilities, TOTP's use of HMAC-SHA1 mitigates these concerns. The secret key prevents attackers from exploiting collision attacks. That said, modern implementations support SHA-256 and SHA-512.

4. Time Synchronization Issues In extreme cases, severe clock drift can cause validation failures. This is rare but worth noting for embedded systems or air-gapped environments.

TOTP vs. Alternative MFA Methods

Comparison

TOTP

Alternative

TOTP vs. SMS OTP

Offline, cryptographically secure, no SIM swap vulnerability

Network-dependent, vulnerable to interception, relies on telecom security

TOTP vs. HOTP (Counter-based)

Time-synchronized, automatically expires

Counter-based, requires synchronization, risk of desync

TOTP vs. Push Notifications

Works offline, faster, no dependency on notification services

More user-friendly, vulnerable to notification spoofing

TOTP vs. Hardware Tokens

Software-based, free, works on phones

Dedicated device, more tamper-resistant, additional cost

The Internet-Free Magic

Let me emphasize why the offline nature is so impressive

Your phone and the server are generating identical codes at identical times without ever talking to each other. They agreed on a secret once during setup, and from that point on, they're just following the same mathematical rules with the same inputs.

Think about it, you can be in airplane mode, in a different timezone, on a submarine - it doesn't matter. As long as your device clock is reasonably accurate, you can authenticate.

This is possible because:

  1. Unix time is a global standard

  2. Both devices have the shared secret

  3. The HMAC-SHA1 algorithm is deterministic

  4. The RFC 6238 specification ensures consistent implementation

Real-World Impact

TOTP has become omnipresent because it hits the sweet spot:

  • Secure enough: Dramatically better than passwords alone

  • User-friendly enough: One extra step, but manageable

  • Accessible enough: Free apps available for all platforms

  • Reliable enough: Works without infrastructure dependencies

Major platforms using TOTP include Google, GitHub, AWS, Microsoft, Dropbox, and thousands of others. It's become in fact the standard for consumer-facing MFA.

Conclusion

TOTP represents elegant engineering, taking complex cryptographic primitives and making them practical for everyday use. It proves that security doesn't always require complexity - sometimes the best solutions are those that cleverly combine simple, well-understood components.

The fact that your phone can generate valid authentication codes without internet access, potentially on the other side of the world from the server, using nothing but shared mathematics and synchronized time, is a testament to thoughtful protocol design.

For engineers, TOTP offers valuable lessons:

  • Leverage existing standards (Unix time, cryptographic hashes)

  • Design for the real world (offline operation, clock drift tolerance)

  • Balance security with usability

  • Keep protocols simple and verifiable

As we move toward passwordless authentication and more advanced methods like FIDO2, TOTP remains relevant as a practical, proven solution that any developer can implement and any user can understand.

Thank you for reading the article. If you found it informative or interesting, please give it a thumbs up. I would highly appreciate it if you could share it with your friends as well.