Time-Based One-Time Password (TOTP) Generator
Time-Based One-Time Passwords (RFC 6238) derive 6-digit codes by hashing the current 30-second time epoch window with a base32-encoded shared secret via HMAC-SHA1. Dynamic truncation extracts a 31-bit integer, and modulo 1,000,000 yields the zero-padded authenticator code.
import hmac, hashlib, struct
counter = int(time.time() // 30)
h = hmac.new(key, struct.pack('>Q', counter), hashlib.sha1).digest()
offset = h[-1] & 0x0F
code = struct.unpack('>I', h[offset:offset+4])[0] & 0x7FFFFFFF
totp = str(code % 1000000).zfill(6)
# Time-Based One-Time Password (TOTP) Generator When users scan a QR code into Google Authenticator or 1Password, the app receives a base32-encoded secret string. The server and the authenticator app don't exchange messages across the internet; they independently compute the exact same 6-digit number at the exact same second. 🛡️📱 The **TOTP algorithm (RFC 6238)** works in 4 steps: 1. **Time Counter**: Divide the Unix timestamp by 30 seconds: $C = \lfloor \text{time} / 30 \rfloor$. Pack as an 8-byte big-endian integer (`>Q`). 2. **HMAC-SHA1**: Compute $H = \text{HMAC-SHA1}(\text{Secret}, C)$. 3. **Dynamic Truncation**: Use the last 4 bits of the hash ($H[19] \ \& \ \text{0x0F}$) as a byte offset. Extract 4 bytes from that offset and mask with `0x7FFFFFFF` to clear the sign bit. 4. **Modulo**: $\text{Code} = (\text{Truncated} \pmod{10^6})$, formatted as a 6-digit zero-padded string. ```python import hmac import hashlib import struct counter = int(time.time()) // 30 h = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest() offset = h[-1] & 0x0F binary = struct.unpack(">I", h[offset:offset+4])[0] & 0x7FFFFFFF otp = str(binary % 1000000).zfill(6) ``` ## Pop Quiz Why does TOTP mask the extracted 4-byte integer with `0x7FFFFFFF` during dynamic truncation? - [ ] To clear the sign bit, preventing ambiguity from signed versus unsigned 32-bit integer modulo arithmetic. - [ ] To encrypt the authenticator code against memory-scraping malware. - [ ] Because SHA-1 produces negative hash digests on 64-bit systems. - [ ] To ensure the resulting code consists exclusively of prime numbers. ## Real-World Challenge Implement `generate_totp(secret_base32: str, current_time: int = None, step: int = 30) -> str`. - Decode `secret_base32` using `base64.b32decode(..., casefold=True)`. - Use `current_time` if provided, else `time.time()`. - Return the RFC-compliant 6-digit string code. <details> <summary>Solution</summary> ```python import hmac import hashlib import struct import time import base64 def generate_totp(secret_base32: str, current_time: int = None, step: int = 30) -> str: # Normalize and decode base32 secret key = base64.b32decode(secret_base32.upper(), casefold=True) ts = int(time.time()) if current_time is None else int(current_time) counter = ts // step # 8-byte big-endian time counter msg = struct.pack(">Q", counter) digest = hmac.new(key, msg, hashlib.sha1).digest() # Dynamic truncation using lowest 4 bits of the last byte offset = digest[-1] & 0x0F code_int = struct.unpack(">I", digest[offset : offset + 4])[0] & 0x7FFFFFFF otp = code_int % 1000000 return str(otp).zfill(6) # Verification # RFC 6238 official test secret (Base32 representation of ASCII '12345678901234567890') rfc_secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" # RFC 6238 Appendix B test vector: at Unix timestamp 59, counter=1, code is 287082 code_59 = generate_totp(rfc_secret, current_time=59) assert code_59 == "287082", f"Expected 287082, got {code_59}" # Test at timestamp 1111111109, code is 081804 code_huge = generate_totp(rfc_secret, current_time=1111111109) assert code_huge == "081804", f"Expected 081804, got {code_huge}" ``` </details>