Message Authentication Codes with hmac.new
HMAC (Hash-based Message Authentication Code) verifies both data integrity and message authenticity using a shared secret key 📜.
import hmac, hashlib
secret_key = b"signing-secret-key"
payload = b"transaction_id=9871&amount=500"
signature = hmac.new(secret_key, payload, hashlib.sha256).hexdigest()
print(f"HMAC Signature: {signature} 📜")
# 115. Message Authentication Codes with hmac.new HMAC (Hash-based Message Authentication Code) verifies both data integrity and message authenticity using a shared secret key 📜. ```python import hmac, hashlib secret_key = b"signing-secret-key" payload = b"transaction_id=9871&amount=500" signature = hmac.new(secret_key, payload, hashlib.sha256).hexdigest() print(f"HMAC Signature: {signature} 📜") ``` Webhook providers (Stripe, GitHub) use HMAC signatures in HTTP headers to prove that webhooks actually originated from them and weren't tampered with! 📜 --- ### Question What two things does an HMAC signature guarantee? 🧠- [ ] a. Data integrity (not tampered with) and message authenticity (sent by secret key holder) 📜 - [ ] b. Data compression and low network latency - [ ] c. Automatic database indexing and replication - [ ] d. AES-GCM payload encryption --- ### Challenge Import `hmac` and `hashlib`. Create HMAC-SHA256 signature for key `b'k'` and message `b'm'`. Print its `.hexdigest()`. 🎯 <details> <summary>Solution</summary> ```python import hmac, hashlib sig = hmac.new(b"k", b"m", hashlib.sha256).hexdigest() print(sig) ``` </details>