Verify message tags with HMAC

A sender attaches an HMAC tag to every message. The receiver recomputes the tag with the shared key and accepts only matching messages.

What to build

A program that checks the tag of each message.

Requirements

  • The tag is the HMAC-SHA256 of the message (UTF-8) with the key, as 64 lower case hex digits.
  • For each message line message tag, print valid if the tag matches and invalid if not.

Input

Line 1: the key. Line 2: n. Then n lines message tag; the message has no spaces.

Output

n lines, valid or invalid.

Constraints

1 ≤ n ≤ 20.

Example

Input:

secret
2
pay:10 516723b797043329e72e22c4b065a0dfed109f640885d1d8b04b77aa62591403
pay:100 516723b797043329e72e22c4b065a0dfed109f640885d1d8b04b77aa62591403

Output:

valid
invalid

Why it works

Without the key an attacker cannot compute a matching tag, and changing the message or the tag makes the recomputed tag differ. compare_digest checks equality without leaking timing information.

Examples

Example 1 · Input
secret
2
pay:10 516723b797043329e72e22c4b065a0dfed109f640885d1d8b04b77aa62591403
pay:100 516723b797043329e72e22c4b065a0dfed109f640885d1d8b04b77aa62591403
Expected output
valid
invalid
Example 2 · Input
secret
1
pay:100 b475843adbff6e705ad2cef641653ac517dbace314ccd78646cacb013ad3d6a3
Expected output
valid

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Use hmac.new(key.encode(), message.encode(), hashlib.sha256).hexdigest() to make the tag you expect.

Hint 2

Compare with hmac.compare_digest(expected, received); it needs two strings of the same kind.

Hint 3

Read the key as a whole line (it may contain a space); each message line is the message, a space and the tag.

Solution

Show one correct solution (try it yourself first)
import hashlib
import hmac

key = input()
n = int(input())
for _ in range(n):
    message, tag = input().split()
    expected = hmac.new(key.encode("utf-8"), message.encode("utf-8"), hashlib.sha256).hexdigest()
    print("valid" if hmac.compare_digest(expected, tag.lower()) else "invalid")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Network security basics: hashes, keys and TLS →