Verify Webhook Signatures With hmac.Equal

Sign canonical webhook payloads using crypto/hmac with SHA-256 and validate hex signatures in constant time via hmac.Equal against tampering.

GoSecurity Boundaries

Code

snippet
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
)

func signWebhook(secret []byte, timestamp, payload string) string {
	mac := hmac.New(sha256.New, secret)
	mac.Write([]byte(timestamp))
	mac.Write([]byte("."))
	mac.Write([]byte(payload))
	return hex.EncodeToString(mac.Sum(nil))
}

func verifyWebhook(secret []byte, timestamp, payload, sigHex string) bool {
	provided, err := hex.DecodeString(sigHex)
	if err != nil {
		return false
	}
	mac := hmac.New(sha256.New, secret)
	mac.Write([]byte(timestamp))
	mac.Write([]byte("."))
	mac.Write([]byte(payload))
	expected := mac.Sum(nil)
	return hmac.Equal(expected, provided)
}

func main() {
	secret := []byte("whsec_demo_signing_key")
	ts := "1732435200"
	body := `{"event":"invoice.paid","amount":4200}`

	sig := signWebhook(secret, ts, body)
	fmt.Println("signature prefix:", sig[:16])
	fmt.Println("valid signature:", verifyWebhook(secret, ts, body, sig))
	fmt.Println("tampered body:", verifyWebhook(secret, ts, `{"event":"invoice.paid","amount":1}`, sig))
	fmt.Println("tampered ts:", verifyWebhook(secret, "1732435201", body, sig))
	fmt.Println("malformed hex:", verifyWebhook(secret, ts, body, "not-hex!"))
}

Execution path — Verify Webhook Signatures With hmac.Equal

Verify Webhook Signatures With hmac.Equal is built around the functions signWebhook, verifyWebhook and main.

Error handling is inline: 1 place test err != nil and branch immediately.

Points of care

  • Package management plays zero part — every symbol belongs inside stock runtime APIs.

Putting it to use

Signature: func signWebhook(secret []byte, timestamp, payload string) string

Output lines are prefixed (signature prefix:, valid signature:, tampered body:), highlighting how every branch updates output during the run.

main calls 2 helpers in sequence: signWebhook and verifyWebhook.

Core lines

func signWebhook(secret []byte, timestamp, payload string) string {
	mac := hmac.New(sha256.New, secret)
	mac.Write([]byte(timestamp))
	mac.Write([]byte("."))
	mac.Write([]byte(payload))
	return hex.EncodeToString(mac.Sum(nil))
}
if err != nil {
	return false
}
return hmac.Equal(expected, provided)

Interactive Tools for This Topic

FAQ

What does Verify Webhook Signatures With hmac.Equal print when run?
The script runs standalone; its 5 labeled outputs include `signature prefix:`, `valid signature:`, `tampered body:`.