Authentication & MFA (TOTP)
Authentication answers "who are you?"; authorization (a later lesson) answers "what may you do?". Authentication is based on one or more factors:
| Factor | Examples | Weakness |
|---|---|---|
| Something you know | Password, PIN, security answer | Phished, guessed, reused, leaked |
| Something you have | Phone app, security key, smart card | Can be lost or stolen |
| Something you are | Fingerprint, face | Can't be changed if copied; needs a fallback |
Multi-factor authentication (MFA) requires factors from at least two different categories. A password plus a security question is still one factor (both are things you know). MFA is one of the most effective controls there is: a stolen or reused password alone no longer gets an attacker in.
Comparing MFA methods
| Method | How it works | Phishing-resistant? | Notes |
|---|---|---|---|
| SMS / voice code | Code sent to your phone number | No | SIM-swap attacks; better than nothing |
| TOTP app | App computes a code from a shared secret and the time | No | Codes can be phished in real time |
| Push approval | Tap "approve" on your phone | No | Vulnerable to "MFA fatigue" spam; use number matching |
| Passkeys / FIDO2 security keys | Public-key signature bound to the site's origin | Yes | The browser won't sign for a look-alike domain |
Passkeys (WebAuthn) are the strongest option because the browser includes the real website origin in what is signed, so a phishing site can't relay the login. TOTP is still extremely common, and it is a nice piece of cryptography to build yourself.
How TOTP works
TOTP (Time-based One-Time Password, RFC 6238) builds on HOTP (RFC 4226):
- During enrolment the server creates a random secret and shows it to the user as a QR code. Both the authenticator app and the server store it.
- Time is divided into 30-second steps:
counter = floor(unix_time / 30). - The code is
HMAC-SHA1(secret, counter), "dynamically truncated" to a 31-bit number, then reduced to 6 (or 8) digits.
Because both sides know the secret and the time, they compute the same code without any communication.
import hmac
import hashlib
import struct
def hotp(secret: bytes, counter: int, digits: int = 6, algo=hashlib.sha1) -> str:
mac = hmac.new(secret, struct.pack(">Q", counter), algo).digest()
offset = mac[-1] & 0x0F # dynamic truncation
number = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
return str(number % 10 ** digits).zfill(digits)
def totp(secret: bytes, unix_time: int, step: int = 30, digits: int = 6) -> str:
return hotp(secret, unix_time // step, digits)
# Test vectors from RFC 6238, Appendix B (SHA-1, 8 digits)
secret = b"12345678901234567890"
vectors = [(59, "94287082"), (1111111109, "07081804"), (1111111111, "14050471"),
(1234567890, "89005924"), (2000000000, "69279037"), (20000000000, "65353130")]
for t, expected in vectors:
code = totp(secret, t, digits=8)
print(f"t={t:<12} {code} {'ok' if code == expected else 'WRONG'}")t=59 94287082 ok
t=1111111109 07081804 ok
t=1111111111 14050471 ok
t=1234567890 89005924 ok
t=2000000000 69279037 ok
t=20000000000 65353130 ok
Checking an implementation against the official test vectors is good practice for any cryptographic code.
Enrolment: the secret and the QR code
Authenticator apps receive the secret as a Base32 string inside an otpauth:// URI, which is what the QR code encodes:
import base64
from urllib.parse import quote
secret = bytes.fromhex("3132333435363738393031323334353637383930") # DEMO: use secrets.token_bytes(20)
b32 = base64.b32encode(secret).decode().rstrip("=")
uri = (f"otpauth://totp/{quote('TAD Shop:alice@example.com')}"
f"?secret={b32}&issuer={quote('TAD Shop')}&digits=6&period=30")
print(b32)
print(uri)GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ
otpauth://totp/TAD%20Shop%3Aalice%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=TAD%20Shop&digits=6&period=30
The TOTP secret is as sensitive as a password: store it encrypted on the server, and show the QR code only once.
Verifying codes on the server
Clocks drift and users take a few seconds to type, so servers usually accept the code for the current step and one step either side. They must also make each code single-use (reject a code that was already accepted) and rate-limit attempts, because 6 digits is only a million possibilities.
import hmac
import hashlib
import struct
def totp(secret, unix_time, step=30, digits=6):
mac = hmac.new(secret, struct.pack(">Q", unix_time // step), hashlib.sha1).digest()
offset = mac[-1] & 0x0F
number = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
return str(number % 10 ** digits).zfill(digits)
class TotpVerifier:
def __init__(self, secret, window=1, max_failures=5):
self.secret, self.window, self.max_failures = secret, window, max_failures
self.last_used_step = -1
self.failures = 0
def verify(self, code, now):
if self.failures >= self.max_failures:
return "locked: too many attempts"
current = now // 30
for step in range(current - self.window, current + self.window + 1):
if hmac.compare_digest(totp(self.secret, step * 30), code):
if step <= self.last_used_step:
return "rejected: replayed or older code"
self.last_used_step = step
self.failures = 0
return "accepted"
self.failures += 1
return "rejected: wrong code"
secret = b"12345678901234567890"
now = 1767225600 # fixed time: 2026-01-01 00:00:00 UTC
v = TotpVerifier(secret)
print("current code:", totp(secret, now))
print(v.verify(totp(secret, now), now))
print(v.verify(totp(secret, now), now + 5)) # replay
print(v.verify(totp(secret, now - 30), now)) # previous step: older than the code just used
print(v.verify("000000", now + 40))
print(v.verify(totp(secret, now + 30), now + 40)) # next step, still in windowcurrent code: 745690
accepted
rejected: replayed or older code
rejected: replayed or older code
rejected: wrong code
accepted
Other authentication essentials
- Rate limiting and lockout against online guessing, with care not to let attackers lock out real users indefinitely (use increasing delays, CAPTCHAs or per-IP limits).
- Uniform error messages: say "invalid username or password", not "unknown user", so attackers can't enumerate accounts.
- Secure account recovery: recovery flows are often the weakest link; a reset link must be single-use, short-lived and unguessable.
- Re-authentication before sensitive actions (changing the email address, adding a payout account).
- Backup codes for MFA, stored hashed like passwords.
Go further: Multi-Factor Authentication and TOTP shows where TOTP verifiers go wrong, and Passkeys and WebAuthn Concepts covers phishing-resistant sign-in.
Test yourself
Which combination is true multi-factor authentication?
- Password + security question
- Password + TOTP code from a phone app
- Two different passwords
- Username + password
In TOTP, what is the HMAC computed over?
- The user's password
- The number of 30-second steps since the Unix epoch
- The IP address
- A random nonce sent by the server
Which MFA method resists phishing because it is bound to the site's origin?
- SMS codes
- TOTP
- Push approval
- Passkeys / FIDO2 security keys