Recipe 7.3 · Python
Hashing and HMAC with SHA-256
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
You need to check that a file wasn't corrupted in transfer, or that a webhook request really came from your payment provider and wasn't altered. The legacy code uses MD5 for the first and a shared secret in a query string for the second.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
Requirements: Python 3.12+. Install: pip install fastapi
"""MD5 file checksum and a webhook secret compared with ==
Source: ImproveCode, Chapter 7, Recipe 7.3 "Hashing and HMAC with SHA-256"
Section: The way it's often written
Book page: 147 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
The ASP.NET Request is modelled as a FastAPI Request; the fragment is wrapped in a function.
"""
import hashlib
from collections.abc import Callable
from fastapi import Request
async def handle(request: Request, path: str,
process_webhook: Callable[[bytes], None]) -> str:
# Not this: MD5 checksum, and a "secret" compared with ==.
with open(path, "rb") as f:
checksum = "-".join(f"{b:02X}" for b in hashlib.md5(f.read()).digest())
if request.query_params.get("key") == "abc123":
process_webhook(await request.body())
return checksum
The improved recipe
Use SHA-256 for checksums and HMAC-SHA-256 with a timestamp for message authentication. Compare
signatures with FixedTimeEquals.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""SHA-256 checksums and HMAC-SHA-256 webhook signing with replay window
Source: ImproveCode, Chapter 7, Recipe 7.3 "Hashing and HMAC with SHA-256"
Section: The improved recipe
Book page: 148-149 -- original C# listing
Converted from C# to Python.
hashlib/hmac replace SHA256/IncrementalHash; hashlib.file_digest is run in a
thread via asyncio.to_thread; TimeProvider becomes an injectable clock callable.
"""
import asyncio
import hashlib
import hmac
import time
from collections.abc import Callable
from datetime import timedelta
class Checksums:
@staticmethod
async def sha256_of_file_async(path: str) -> str:
def _hash() -> str:
with open(path, "rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest().upper()
return await asyncio.to_thread(_hash)
@staticmethod
def sha256_of_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest().upper()
class WebhookSigner:
"""Signs and verifies "{timestamp}.{body}" with HMAC-SHA-256, the
scheme most webhook providers use."""
def __init__(self, secret: bytes,
clock: Callable[[], float] = time.time,
tolerance: timedelta | None = None) -> None:
if secret is None:
raise TypeError("secret")
if len(secret) < 32:
raise ValueError("secret must be at least 32 bytes")
self._secret = bytes(secret)
self._clock = clock
self._tolerance = tolerance or timedelta(minutes=5)
def sign(self, body: bytes, unix_seconds: int) -> str:
return self._compute(body, unix_seconds).hex().upper()
def is_valid(self, body: bytes, unix_seconds: int, signature: str) -> bool:
now = int(self._clock())
if abs(now - unix_seconds) > self._tolerance.total_seconds():
return False # too old or from the future: replay
try:
provided = bytes.fromhex(signature)
except ValueError:
return False
expected = self._compute(body, unix_seconds)
return hmac.compare_digest(expected, provided)
def _compute(self, body: bytes, unix_seconds: int) -> bytes:
prefix = f"{unix_seconds}."
mac = hmac.new(self._secret, digestmod=hashlib.sha256)
mac.update(prefix.encode("ascii"))
mac.update(body)
return mac.digest()
How it works
A hash is a fingerprint: anyone can compute it, and any change to the input changes it. That
makes SHA-256 right for detecting accidental corruption and for content-addressed caching, but
useless for proving who sent a message, because an attacker who changes the file can recompute the
hash too. HashDataAsync streams the file, so a 4 GB export doesn't need 4 GB of memory.
An HMAC mixes a secret key into the hash. Only someone who has the key can produce a valid
signature, and changing a byte of the body invalidates it. The sender computes
HMAC(secret, timestamp + "." + body) and sends the timestamp and signature in headers; the
receiver recomputes and compares.
The timestamp is part of the signed content, so it can't be altered, and the tolerance check
rejects requests replayed more than five minutes later. Injecting TimeProvider (built in since
.NET 8) makes that check testable with a fake clock.
FixedTimeEquals matters here more than anywhere else. The signature is compared against
attacker-controlled input on every request, which is exactly the situation where early-exit
comparison could leak information through timing. It also returns false for arrays of
different lengths, so a truncated signature fails cleanly.
Variations and pitfalls
- Sign the raw request body bytes exactly as received. If you deserialize and reserialize the JSON first, whitespace or property order changes and valid signatures fail.
- In ASP.NET Core, call
Request.EnableBuffering(), read the body into a byte array for the check, then rewind the stream if model binding needs it. - Follow each provider's documented scheme exactly. Some sign only the body, some use Base64 instead of hex, some include the URL. The class above is the common pattern, not a standard.
- Don't use plain SHA-256 to "hash" a secret for storage when the secret has low entropy, such as a password or a PIN. That is Recipe 7.1's job. SHA-256 is fine for high-entropy random tokens (Recipe 7.4).
- MD5 and SHA-1 are acceptable only for non-security uses such as matching a legacy system's checksum format. Mark those call sites with a comment so the next reviewer doesn't have to guess.