Predict the output
What do the three verify calls print?
import hashlib
import hmac
import time
SECRET = b"whsec_test_only"
def sign(body: bytes, ts: int) -> str:
msg = str(ts).encode() + b"." + body
return hmac.new(SECRET, msg, hashlib.sha256).hexdigest()
def verify(body: bytes, ts: int, sig: str, now: int) -> bool:
if abs(now - ts) > 300:
return False
return hmac.compare_digest(sign(body, ts), sig)
now = int(time.time())
body = b'{"event": "invoice.paid", "id": "evt_1"}'
good = sign(body, now)
print(verify(body, now, good, now))
print(verify(body + b" ", now, good, now))
print(verify(body, now - 3600, sign(body, now - 3600), now))Hint 1 of 1
Two checks: the window and the HMAC.
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A True, False, False
Correct. The tampered body fails the HMAC; the hour-old timestamp is outside the 5-minute window.
verify checks two things: the timestamp is within 300 s of now, and the HMAC over timestamp and body matches. The extra space changes the body; the third call is signed correctly but is an hour old.
Why not the others?
- B
True,True,True. A single extra byte changes the HMAC. - C
True,False,True. The third signature is valid, but the timestamp is too old. - D
False,False,False. The first call uses a fresh, correct signature.