Build a Python TOTP Generator: Your Own Offline 2FA Codes (Full Code)
Every time you open an authenticator app and see a six-digit code that changes every 30 seconds, you’re watching a small piece of cryptography do its job. That system is called TOTP — Time-based One-Time Password — and it’s simple enough to build yourself in about 60 lines of Python. Doing so teaches you exactly how two-factor authentication works under the hood.
How TOTP Works
Three ingredients:
- A shared secret — a random key you and the server both know, usually delivered as a QR code when you set up 2FA.
- The current time — divided into 30-second windows. Both sides compute the same window, so they agree on the code.
- HMAC-SHA1 — a keyed hash that mixes the secret with the time window, then gets truncated to six digits.
The server checks the code you type against the one it computes for the current window (usually accepting the previous and next window too, for clock drift). No network needed, no SMS, nothing to intercept in transit.
The Code
import base64import hashlibimport hmacimport structimport timedef generate_totp(secret_b32: str, digits: int = 6, period: int = 30) -> str: """Generate the current TOTP code for a base32 secret.""" key = base64.b32decode(secret_b32.upper()) counter = int(time.time()) // period msg = struct.pack(">Q", counter) digest = hmac.new(key, msg, hashlib.sha1).digest() # Dynamic truncation (RFC 4226) offset = digest[-1] & 0x0F code = struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7FFFFFFF return str(code % (10 ** digits)).zfill(digits)def time_remaining(period: int = 30) -> int: return period - (int(time.time()) % period)if __name__ == "__main__": secret = input("Paste your base32 secret: ").strip() code = generate_totp(secret) print(f"\nYour code: {code}") print(f"Valid for {time_remaining()} more seconds")
Save it as totp.py and run python3 totp.py. Paste a base32 secret (the string behind any authenticator QR code) and it prints the same six digits your authenticator app shows. Try it against a real account’s secret and watch them match — that’s the moment the magic dies and the understanding begins.
How It Works, Line by Line
- Decode the secret — base32 is just a text-friendly way to store the raw key bytes.
- Build the counter — the current Unix time divided by 30 gives the time window both sides agree on.
- HMAC-SHA1 — the secret signs the counter, producing 20 bytes that look random.
- Dynamic truncation — the last nibble of the hash picks a 4-byte slice, which becomes a big number.
- Modulo 1,000,000 — the number is reduced to six digits and zero-padded.
Use It Safely
- This is a learning tool. For real accounts, keep using a proper authenticator app with encrypted storage.
- Never paste a real secret into a shared machine or a screenshot — anyone with the secret can generate your codes forever.
- Never share your secret or your codes with anyone, including “support” — real support never asks for them.
- Only test systems you own or have written permission to test.
Level Up
- Add a loop that refreshes the code every second and shows a countdown bar.
- Accept the previous and next time window when verifying, like real servers do — that’s a one-line change to the counter.
- Store secrets encrypted with a master password instead of pasting them each time.
You just rebuilt a core piece of modern authentication from scratch. That’s the fastest way to truly understand 2FA — and to explain it to anyone else.



Comments
Post a Comment