Logo
Logo
Home
Archive
AI Agent Notes
Advertise
YouTube
Login
Sign Up
Logo
  • Home
  • Posts
  • 🦥 How Do Two-Factor Codes Work?

🦥 How Do Two-Factor Codes Work?

Aug 26, 2025

Sponsored by

Hello friends!

Welcome to this week’s Sloth Bytes. I hope you had a fun week.

Unlock the Power of AI With the Complete Marketing Automation Playbook

Discover how to reclaim your time and scale smarter with AI-driven workflows that actually work. You’ll get frameworks, strategies, and templates you can put to use immediately to streamline and supercharge your marketing:

  • A detailed audit framework for your current marketing workflows

  • Step-by-step guidance for choosing the right AI-powered automations

  • Pro tips for improving personalization without losing the human touch

  • Tools and templates to speed up implementation

Built to help you automate the busywork and focus on work that actually makes an impact.

Steal the Playbook

How Do Two-Factor Codes Work?

You know the drill: you log into a website/app, it asks for your password, and then it demands that six-digit code from your phone. You punch it in, it works, and you move on with your day.

But how does that work? Is it even doing anything?

The Secret Behind the Codes

When you set up authenticator-app 2FA, the service usually shows you a QR code and your authenticator app scans it.

That QR isn’t just a random blob.

That QR usually encodes a provisioning URI containing a shared secret plus metadata such as the account name, issuer, algorithm, digit count, and time period. Your authenticator stores the secret, and the service needs access to the same secret to verify future TOTP codes. Unlike a password hash, that server-side TOTP secret must remain usable—so it should be encrypted/protected at rest and access to it should be tightly restricted.

But how do those one-time codes work?

Time-Based One-Time Passwords (TOTP)

Authenticator-app codes commonly use Time-Based One-Time Passwords (TOTP). SMS and push approvals are different mechanisms, even though people casually lump all of them together as “2FA codes.”

  1. Take the shared secret provisioned during setup.

  2. Convert the current Unix time into a moving counter. RFC 6238 recommends a 30-second default time step.

  3. Compute an HMAC over that counter using the shared secret. TOTP was defined around HMAC-SHA-1, while SHA-256 and SHA-512 are also supported by the standard.

  4. Dynamically truncate the HMAC result and reduce it to a short numeric code, commonly 6 digits.

  5. The server independently calculates the expected code and may accept a very small neighboring time window for clock drift/network delay.

💻 A Mini Example in Python

Here’s a tiny Python demo. Do not log or display real TOTP secrets in production; this is just showing the mechanics:

import pyotp

# Demo only: generate a secret during enrollment.
# In a real app, protect this value and never log it.
secret = pyotp.random_base32()
totp = pyotp.TOTP(secret)

current_code = totp.now()
print("Current demo code:", current_code)

# Server-side verification of a submitted code:
is_valid = totp.verify(current_code)
print("Valid:", is_valid)

With the common defaults, a new code is generated for each 30-second time step. The exact period, number of digits, and algorithm are system parameters—not laws of nature.

One-Time Should Actually Mean One-Time

A subtle implementation mistake is accepting the same valid TOTP repeatedly during its time window. After a code is successfully used, the verifier should remember enough state to reject a replay of that same OTP while it is still valid.

You also need rate limiting. Six digits only gives about a million possible codes, so an endpoint that allows unlimited guesses has built a very enthusiastic brute-force API.

Clock skew: be tolerant, not generous

Servers often accept the current time step plus a small neighboring window to tolerate clock drift and network delay. Making that window huge improves usability by weakening the whole “short-lived code” property. RFC 6238 recommends keeping the allowed delay narrow.

TOTP is not phishing-resistant

TOTP is much better than a password alone, but a fake login page can still ask you for the current code and relay it to the real site before it expires. Manual OTP entry does not cryptographically bind the authentication to the legitimate domain/session.

Other Types of 2FA

Not all 2FA is TOTP:

  • SMS codes: Usually better than a password alone, but vulnerable to phishing, SIM swapping, number takeover, and telecom/account-recovery attacks.

  • Push-based authentication: Approve a login in an app. Good implementations add protections such as number matching, device/context details, and rate limits to reduce push-fatigue attacks.

  • TOTP authenticator apps: Offline, widely supported, and replay-limited when implemented correctly—but still phishable because you manually type the code into a website.

  • FIDO2/WebAuthn security keys or passkeys: Phishing-resistant authentication because the cryptographic credential is bound to the legitimate site instead of asking you to copy a reusable secret/code between sites.

Don’t Forget Recovery

Your authentication system also needs a safe recovery story. Backup codes should be high-entropy, single-use secrets stored like passwords when practical, and users should be able to revoke/reset authenticators after losing a device. Recovery is part of the security model—an ultra-secure second factor with a weak “email support and tell us your birthday” reset flow is security theater with extra steps.

If you want to keep learning

  • How passwords actually work — understand hashing and salting before the second authentication factor even kicks in.

  • How environment variables and secrets leak — TOTP depends on shared secrets, so storing and protecting those secrets matters just as much as generating the codes.

  • How random numbers work in programming — authentication secrets and recovery tokens need cryptographically secure randomness, not just a normal PRNG.

Thanks for the feedback!

Coinbase CEO explains why he fired engineers who didn’t try AI immediately

After getting licenses to cover every engineer, some at the cryptocurrency exchange warned Armstrong that adoption would be slow.

SpyVPN: The Google-Featured VPN That Secretly Captures Your Screen

FreeVPN.One, a Chrome-verified extension with over 100K installs, claimed to offer privacy but instead captured users’ screens.

The Month of AI Bugs

An initiative to raise awareness of security vulnerabilities in agentic AI systems.

We studied 100 dev tool landing pages—here’s what really works in 2025

While designing a landing page template for dev tool startups, we reviewed 100+ real product sites.

Why Was Apache Kafka Created?

The story behind how LinkedIn created Apache Kafka

Thanks to everyone who submitted!

GodOfjiz, gcavelier, ProAnshu, Pocket04, soren-martin, RISHI-GAPPIBHAI, akshaysreekrishna-byte, 190-785, AspenTheRoyal, NeoScripter, Suji-droid, and Dennis-Bauer.

Valid Hex Code

Create a function that determines whether a string is a valid hex code.

A hex code must begin with a pound key # and is exactly 6 characters in length.

Each character must be a digit from 0-9 or an alphabetic character from A-F. All alphabetic characters may be uppercase or lowercase.

Examples

is_valid_hex_code("#CD5C5C")
output = True

is_valid_hex_code("#EAECEE")
output = True

is_valid_hex_code("#eaecee")
output = True

is_valid_hex_code("#CD5C58C")
output = False
# Length exceeds 6

is_valid_hex_code("#CD5C5Z")
output = False
# Not all alphabetic characters in A-F

is_valid_hex_code("#CD5C&C")
output = False
# Contains unacceptable character

is_valid_hex_code("CD5C5C")
output = False
# Missing #

How To Submit Answers

Reply with

  • A link to your solution (github, twitter, personal blog, portfolio, replit, etc)

  • If you’re on the web version leave a comment!

  • If you want to be mentioned here, please send a submission link not the code!

That’s all from me!

Have a great week, be safe, make good choices, and have fun coding.

If I made a mistake or you have any questions, feel free to comment below or reply to the email!

See you all next week.

What'd you think of today's email?

  • 🦥 Amazing! Keep it up
  • 🦥 Good, not great
  • 🦥 It sucked

Login or Subscribe to participate

Want to advertise in Sloth Bytes?

If your company is interested in reaching an audience of developers and programming enthusiasts, you may want to advertise with us here.

Keep Reading

Read all
arrow-right
envelope-simple

Join 50k+ developers and become a better programmer and stay up to date in just 5 minutes.

© 2026 Sloth Bytes.
beehiivPowered by beehiiv