On this page
  1. hmac
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Verifying an Incoming Webhook Signature Safely
  7. 2. Streaming Large Payloads Incrementally
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

hmac

Prev: heapq | Up: stdlib_module | Next: html
Rel: hashlib, secrets
Ref: docs.python.org — hmac
Tags: #public #python3 #stdlib


Import

import hmac

Overview

Keyed-Hash Message Authentication Code (RFC 2104) combining a secret key with a cryptographic hash from hashlib (such as SHA-256) to verify both message integrity and authenticity. Essential for signing and verifying webhook payloads, API requests, and tamper-evident tokens.

Quick Start

import hmac

secret = b"shared-webhook-secret"
body = b'{"event":"release","tag":"v0.1.0"}'

sig = hmac.digest(secret, body, "sha256").hex()
expected = hmac.digest(secret, body, "sha256").hex()
assert hmac.compare_digest(sig, expected)

Implementation Walkthrough

1. Verifying an Incoming Webhook Signature Safely

import hashlib
import hmac

def sign_payload(secret: bytes, payload: bytes) -> str:
    return "sha256=" + hmac.new(secret, payload, hashlib.sha256).hexdigest()

def verify_payload(secret: bytes, payload: bytes, header_sig: str) -> bool:
    expected = sign_payload(secret, payload)
    return hmac.compare_digest(expected.encode("ascii"), header_sig.encode("ascii"))

key = b"top-secret"
msg = b"hello"
hdr = sign_payload(key, msg)
assert verify_payload(key, msg, hdr)
assert not verify_payload(key, b"tampered", hdr)

2. Streaming Large Payloads Incrementally

import hashlib
import hmac

mac = hmac.new(b"secret", digestmod=hashlib.sha256)
for chunk in (b"part-1-", b"part-2"):
    mac.update(chunk)
tag = mac.hexdigest()

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes