HMAC Generator
Generate HMAC signatures from message and secret key using SHA-256/384/512.
Frequently Asked Questions
Code Implementation
import hmac
import hashlib
import base64
import secrets
# Generate HMAC-SHA256
key = secrets.token_bytes(32) # 256-bit random key
message = "Hello, World!"
# Raw hex output
mac = hmac.new(key, message.encode(), hashlib.sha256)
print("HMAC-SHA256 (hex):", mac.hexdigest())
# Base64 output (common for API signatures)
mac_b64 = base64.b64encode(mac.digest()).decode()
print("HMAC-SHA256 (b64):", mac_b64)
# HMAC-SHA512
mac512 = hmac.new(key, message.encode(), hashlib.sha512)
print("HMAC-SHA512 (hex):", mac512.hexdigest())
# Constant-time verification (prevents timing attacks)
def verify_hmac(key: bytes, message: str, expected: str) -> bool:
computed = hmac.new(key, message.encode(), hashlib.sha256).hexdigest()
return hmac.compare_digest(computed, expected)
signature = mac.hexdigest()
print("Valid: ", verify_hmac(key, message, signature)) # True
print("Invalid:", verify_hmac(key, "tampered", signature)) # FalseComments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.