~/ learn/ comp-400/ cards/ MACs, keyed hashes, and HMAC
1 of 8

Build HMAC-SHA-256 by hand from the RFC 2104 pads and check it against Python’s hmac module, then re-run it over a tampered message.

Build HMAC-SHA-256 by hand from the RFC 2104 pads and check it against Python’s hmac module, then re-run it over a tampered message.

Answer

import hashlib, hmac B = 64 KEY = b'shared-key-comp400' MSG = b'transfer 250 to account 4417' def hmac_by_hand(key, msg): if len(key) > B: key = hashlib.sha256(key).digest() kp = key + b'\x00' * (B - len(key)) si = bytes(b ^ 0x36 for b in kp) so = bytes(b ^ 0x5C for b in kp) inner = hashlib.sha256(si + msg).digest() return hashlib.sha256(so + inner).hexdigest() mine = hmac_by_hand(KEY, MSG) lib = hmac.new(KEY, MSG, hashlib.sha256).hexdigest() print('by hand ', mine[:32]) print('library ', lib[:32]) print('agree ', mine == lib) print('tampered', hmac_by_hand(KEY, b'transfer 950 to account 4417')[:32])

Stallings & Brown, Computer Security 5e, ch2 §2.2; ch21 §21.2; RFC 2104

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/d50f63fb-f85a-4249-97e3-8abe9660a075/flashcard utf-8 LF