Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 7 min read

How Authenticator Apps Work (and Why Airplane Mode Doesn't Break Them)

Have you noticed that every app wants you to turn on two-step verification now? Your bank, your email, GitHub, Instagram. Most of us have used the version where a code arrives by SMS or email. But you may also have used

How Authenticator Apps Work (and Why Airplane Mode Doesn't Break Them)

Have you noticed that every app wants you to turn on two-step verification now? Your bank, your email, GitHub, Instagram. Most of us have used the version where a code arrives by SMS or email. But you may also have used the other kind, where you scan a QR code and an app on your phone starts showing a six-digit number that changes every 30 seconds.

That second kind is called TOTP, and it's what Google Authenticator and apps like it do. What makes it odd is that nothing is sent to you. No SMS, no email. The website still knows whether the number you type is right, and it keeps working with airplane mode on.

How does that work? The obvious guess is that the phone and the website are in constant contact. They aren't. After the scan they never talk to each other again, and the rest of this post is about why that's enough.

The idea in four sentences

When you set it up, the website hands your phone a secret, and both keep a copy. Later, each side takes that secret plus the current time and runs the same maths. Same inputs, same six digits. You type yours, the server compares it with its own.

The standard is called TOTP, time-based one-time password (RFC 6238). Google Authenticator, Microsoft Authenticator, Authy and 1Password all follow it, and so does the authenticator option in Twilio Verify. That's why one QR code can work in several different apps.

The QR code is only text

People tend to assume the QR code gets "verified" by something. It doesn't. It's a picture of a line of text:

otpauth://totp/Acme:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Acme&period=30&digits=6

Acme:[email protected] is the label the app displays. issuer, period and digits are settings: who it's from, how long a code lives, how long it is. The only part that matters is secret, a random key written in base32 so it's easy to type. That's also what the "can't scan? enter this key" link shows. Typing it does exactly what scanning does.

(JBSWY3DPEHPK3PXP is the stock example key from docs. A real one is random and different for every user.)

Setting up an authenticator: the website shows a QR code, the phone scans it and starts showing codes, then you type a code to confirm

The app saves the secret and starts producing codes. Then the site asks you to type the current one. That step isn't decoration. It proves the scan worked, so you don't turn on 2-step login with an app that never got the secret and lock yourself out of your own account.

Where the number comes from

Five steps, and none of them touch the network:

  1. Read the current time as seconds since January 1, 1970.
  2. Divide by 30 and drop the remainder. This is the counter. Everything inside the same 30-second window gives the same counter.
  3. Feed the secret and the counter into HMAC-SHA1. Out come 20 bytes that look like random noise.
  4. Use the last byte to pick a starting spot, take four bytes from there, and read them as a number.
  5. Keep the last six digits.

Phone and server both take the same secret and the same 30-second time slot, run the same scramble, and arrive at 260025

The mixing only goes one way. If someone sees 260025 over your shoulder, they can't work back to the secret, and thirty seconds later that code is useless anyway.

Here's the whole thing in Python, no libraries:

import base64, hashlib, hmac, struct, time

def totp(secret_b32, t=None, step=30, digits=6):
    key = base64.b32decode(secret_b32)
    counter = int((time.time() if t is None else t) // step)
    h = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
    offset = h[-1] & 0x0F
    n = struct.unpack(">I", h[offset:offset + 4])[0] & 0x7FFFFFFF
    return str(n % 10**digits).zfill(digits)

print(totp("JBSWY3DPEHPK3PXP"))

I ran it against the test values in the RFC. With the RFC's key 12345678901234567890 at Unix time 59, the 8-digit answer is 94287082. This function with digits=6 gives 287082, the last six digits of that. For the example secret at exactly 2026-01-01 00:00:00 UTC the counter is 58,907,520 and the code is 260025. Thirty seconds on, the counter is 58,907,521 and the code is 307890.

What the server does at login

Exactly what your phone did. It finds the secret it stored for you, reads its own clock, runs the function and compares.

def verify(secret_b32, submitted, window=1):
    now = time.time()
    for drift in range(-window, window + 1):
        if hmac.compare_digest(totp(secret_b32, now + drift * 30), submitted):
            return True
    return False

The loop is there because phone clocks drift and you're slow at typing. Accepting the slot before and after the current one is why a code sometimes still works a few seconds after it vanished from your screen. compare_digest is a constant-time comparison, so timing doesn't hint at how many digits were right.

A careful server does two more things. It refuses a code it has already accepted, so a stolen one can't be replayed inside the window. And it limits wrong guesses, because six digits is only a million possibilities and a script can try a lot of them.

Why it works offline

Look at what each side needs: the secret, which was saved once at setup, and the time, which every phone has. Neither needs to ask anybody anything. In a basement with no signal your phone still computes the right number, since the server will compute the same one from its copy of the secret and its own clock. Only the six digits you type cross the internet.

What breaks offline is the clock. If your phone's time is a few minutes off, you'll get "invalid code" while doing everything right. Switch on automatic time. Google Authenticator on Android also has "Time correction for codes" in its settings for this.

Locking an account, then opening it again

Say Sam wants to protect an account.

Sam opens the security settings, turns on 2-step login and scans the QR code. The app begins showing codes. Sam types the current one into the site, it matches, and 2-step login is now on. A password alone won't get anyone in from here.

A few weeks later Sam logs in. Email and password are accepted, then the site stops and asks for a code. Sam opens the same app, reads whatever it shows right now, and types it. The server derives the same number from the stored secret, sees the match, and lets Sam in.

Three panels: code accepted and 2-step login turned on, the next login asks for a code after the password, then the app shows a new code which unlocks the account

The code from the first day and the code from weeks later are different numbers. Only the secret stays put.

Where it falls short

Whoever has the secret has your codes, including anyone who photographs the QR code during setup. Don't screenshot it or leave it on a shared screen.

If you lose the phone you lose the codes. Save the backup codes the site gives you. Some apps sync secrets to a cloud account (Google Authenticator can now, and Authy does), which makes recovery easier but turns that account into something you have to protect.

TOTP doesn't stop phishing. A fake login page can ask for your code and relay it to the real site inside the 30-second window. It's much better than a password alone, but passkeys and hardware keys handle this case and TOTP doesn't.

Last one, and it's the least obvious. The website has to keep your actual secret.

Passwords work differently. A well-built site never stores your password. It stores a scrambled fingerprint of it, called a hash. When you log in, it scrambles what you typed and checks that the two fingerprints match. It never needs the real password back, so if a thief steals the database, all they get is fingerprints that are very hard to turn back into passwords.

A six-digit code can't be checked that way. To work out the code for this 30-second slot, the server has to run the recipe from earlier with the secret itself. Feed the recipe a fingerprint instead and you get a different, useless number that never matches what your phone shows. So the secret has to be stored in a form the server can read back.

Think of it as a spare key to your house that the site keeps in a cabinet. If a burglar gets into the site and copies everything in that cabinet, they can make your codes from their own laptop, and nothing would look wrong, since their numbers match your phone's numbers.

That's why a site should lock the secrets up (encrypt them) and keep the key to that lock somewhere else, such as a separate key vault. Then a stolen copy of the database is just scrambled noise. And if you hear that a site you use was breached, treat your authenticator entry for it as exposed too. Turn 2-step login off and on again to get a fresh secret and a new QR code, and delete the old entry from your app.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.