~/ learn/ comp-400/ cards/ Tokens, smart cards, and one-time passwords
1 of 7

Implement TOTP as RFC 6238 defines it — floor the time into 30-second steps, HMAC-SHA-1 the step counter under the shared secret, take the dynamic-offset truncation, reduce to six digits. The timestamps are supplied rather than read from a clock, so the output is deterministic; these are the standard test vectors.

Implement TOTP as RFC 6238 defines it — floor the time into 30-second steps, HMAC-SHA-1 the step counter under the shared secret, take the dynamic-offset truncation, reduce to six digits. The timestamps are supplied rather than read from a clock, so the output is deterministic; these are the standard test vectors.

Answer

import hashlib, hmac, struct def totp(key, unix_time, time0=0, step=30, digits=6): counter = (unix_time - time0) // step mac = hmac.new(key, struct.pack('>Q', counter), hashlib.sha1).digest() offset = mac[-1] & 0x0F truncated = struct.unpack('>I', mac[offset:offset + 4])[0] & 0x7FFFFFFF return str(truncated % 10 ** digits).zfill(digits) secret = b'12345678901234567890' for t in (59, 1111111109, 1234567890): print(t, (t - 0) // 30, totp(secret, t))

Stallings & Brown, Computer Security 5e, ch3 §3.3; RFC 6238 and RFC 4226 (the TOTP construction, EXT); NIST SP 800-12 (token drawbacks)

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/5d3c9f53-5ba1-46d4-b44b-32f076377327/flashcard utf-8 LF