Hashing, encoding and basic security · 2 / 15 Theory

Integrity and signatures with HMAC

A hash detects accidental changes, but anyone can recompute it after tampering with the data. To check also who generated it you use an HMAC: a hash that incorporates a shared secret key.

import hashlib, hmac

message = b"transfer 100 to ana"
key = b"shared-secret"

signature = hmac.new(key, message, hashlib.sha256).hexdigest()
print(len(signature))                                                   # 64

# The receiver recomputes the signature with the same key and compares
received = signature
ok = hmac.compare_digest(hmac.new(key, message, hashlib.sha256).hexdigest(), received)
print(ok)                                                           # True

# If someone changes the message, the signature stops being valid
tampered = b"transfer 900 to ana"
forged = hmac.new(key, tampered, hashlib.sha256).hexdigest()
print(hmac.compare_digest(forged, received))                         # False

# Without the key a valid signature cannot be forged
attempt = hmac.new(b"other-key", message, hashlib.sha256).hexdigest()
print(hmac.compare_digest(attempt, received))                       # False

import hashlib
fingerprint = hashlib.sha256(message).hexdigest()    # a plain hash: anyone can compute it
print(fingerprint == hashlib.sha256(message).hexdigest())   # True
  • Publishing the fingerprint next to a download lets you check it has not been corrupted (integrity), but not that it is authentic if the attacker can change both things.
  • hmac.new(key, message, hashlib.sha256) produces the signature. Only whoever has the key can create a valid one.
  • Always compare with hmac.compare_digest, not with ==: the normal comparison ends earlier when it finds a difference and that time can leak information.
  • The key must be long, random and not written in the code: read it from an environment variable or a secrets manager.

You practice it in Check the integrity of a message and Sign messages with HMAC.