Verify a Webhook Signature

Hard ⏱ 18 min 34% acceptance ★★★★☆ 4.4
Payment webhooks must be verified. Write is_valid_webhook(payload_bytes, secret, signature) computing hmac.new(secret.encode(), payload_bytes, hashlib.sha256).hexdigest() and comparing to the given signature with hmac.compare_digest — the constant-time comparison that resists timing attacks.

Examples

Example 1
Input
is_valid_webhook(b'{"amt": 5}', 'whsec_x', received_sig)
Output
True only when the HMAC matches
Explanation

Recompute and compare in constant time.

Constraints

  • Use hmac.compare_digest, never ==.
  • SHA-256 hex digest.

Topics

APIswebhook security

Companies

StripeRazorpayGitHub

Hints

Hint 1

import hmac, hashlib.

Hint 2

The secret is the HMAC key, the payload the message.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.