Last active
July 24, 2024 22:04
-
-
Save bartekpacia/1fd782c50f30c961a7cfb1b353c00e5d to your computer and use it in GitHub Desktop.
Verifying if HMAC digests match in Golang.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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