Skip to content

Instantly share code, notes, and snippets.

@bartekpacia
Last active July 24, 2024 22:04
Show Gist options
  • Save bartekpacia/1fd782c50f30c961a7cfb1b353c00e5d to your computer and use it in GitHub Desktop.
Save bartekpacia/1fd782c50f30c961a7cfb1b353c00e5d to your computer and use it in GitHub Desktop.
Verifying if HMAC digests match in Golang.
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"strings"
)
const (
secret = "It's a Secret to Everybody"
payload = "Hello, World!"
theirSignature = "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17"
)
func main() {
theirDigestHex := strings.Split(theirSignature, "=")[1]
fmt.Println("their digest is:", theirDigestHex)
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(payload))
ourDigest := mac.Sum(nil)
ourDigestHex := hex.EncodeToString(ourDigest)
fmt.Println("our digest is :", ourDigestHex)
fmt.Println("our digest in base64 is:", base64.StdEncoding.EncodeToString(ourDigest))
fmt.Println("our digest is (as bytes):", ourDigest)
theirDigest, err := hex.DecodeString(theirDigestHex)
if err != nil {
fmt.Print("fatal error", err)
return
}
matchOK := hmac.Equal(theirDigest, ourDigest)
fmt.Println("do these digests match?", matchOK)
}
// Based on https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment