Message authentication with HMAC

A message authentication code (MAC) is a short tag computed from a message and a secret key. A receiver who has the same key recomputes the tag. If it matches, the message is intact and came from someone who knows the key. Without the key, an attacker cannot produce a valid tag for a changed message.

Python
import hashlib
import hmac

key = b"shared-secret-key"


def sign(message):
    return hmac.new(key, message, hashlib.sha256).hexdigest()


def verify(message, tag):
    return hmac.compare_digest(sign(message), tag)


message = b"amount=100&to=alice"
tag = sign(message)
print(verify(message, tag))
print(verify(b"amount=900&to=alice", tag))
print(verify(message, "0" * 64))
print(len(tag))
Read the full lesson