How to generate HMAC-SHA256 in Python
Compute an HMAC-SHA256 message authentication code in Python for webhook signatures, API request signing, and understanding HS256 JWT internals. Use the browser HMAC Generator to compare digests while debugging, then implement hmac + hashlib with a strong shared secret and constant-time comparison on verify.
Last updated August 26, 2026
Steps
- 1
Open the HMAC Generator, enter a test message and secret, and select SHA-256.
- 2
Copy the hex digest — computation is client-side for safe local debugging.
- 3
In Python, compute the same digest with hmac + hashlib and confirm it matches the tool.
- 4
When verifying untrusted digests, use a constant-time compare (never == on hex strings alone).
- 5
For production secrets, generate entropy with the JWT Secret Generator and store it outside source control.
Code Example
import hmac
import hashlib
import os
secret = os.environ["HMAC_SECRET"].encode()
message = b"webhook-body-or-signing-input"
digest = hmac.new(secret, message, hashlib.sha256).hexdigest()
# Compare against the browser HMAC Generator when debugging.
# Timing-safe compare for untrusted input:
hmac.compare_digest(digest, incoming_hex)Other languages
Related Articles
Frequently Asked Questions
What is HMAC-SHA256 used for?
HMAC authenticates a message with a shared secret. Common uses include webhook verification, API request signing, and the MAC step inside HS256 JWTs.
How do I verify an HMAC in Python?
Recompute the digest with hmac + hashlib over the exact same bytes the sender signed, then compare with a timing-safe equality helper. Mismatched encoding (hex vs Base64) is a frequent bug.
Is HMAC the same as hashing a password?
No. HMAC is fast and keyed. Password storage needs a slow KDF such as bcrypt, scrypt, or Argon2.
Is the browser HMAC Generator safe?
Yes for debugging — digests are computed locally. Do not paste live production secrets into shared or untrusted browsers.