Skip to content

Instantly share code, notes, and snippets.

@jwhett
Forked from viktorbenei/main.go
Last active October 17, 2022 01:24
Show Gist options
  • Save jwhett/98a482e84c94ea5f80a294197a0cb889 to your computer and use it in GitHub Desktop.
Save jwhett/98a482e84c94ea5f80a294197a0cb889 to your computer and use it in GitHub Desktop.
sha1 hmac hexdigest signature
package main
import (
"crypto/hmac"
"crypto/sha1"
"crypto/subtle"
"encoding/hex"
"fmt"
"os"
)
func generateSignature(secretToken, payloadBody string) string {
mac := hmac.New(sha1.New, []byte(secretToken))
mac.Write([]byte(payloadBody))
expectedMAC := mac.Sum(nil)
return "sha1=" + hex.EncodeToString(expectedMAC)
}
func verifySignature(secretToken, payloadBody string, signatureToCompareWith string) bool {
signature := generateSignature(secretToken, payloadBody)
return subtle.ConstantTimeCompare([]byte(signature), []byte(signatureToCompareWith)) == 1
}
func main() {
testPayloadBody := `{"message":"test content"}`
testSignatureToCompareWith := `sha1=33a08e9b5e9c8d5e944d9288e9b499abb298344d`
fmt.Println("signature match? :", verifySignature(os.Getenv("SECRET_TOKEN"), testPayloadBody, testSignatureToCompareWith))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment