How to generate a SHA256 HMAC in Go
Here is how to do it in Go:
func main() {
// create a random 64 bytes (512 bits) secret
secret := make([]byte, 64)
_, err := rand.Read(secret)
if err != nil {
fmt.Println("error generating a random secret:", err)
return
}
data := []byte("Hello World")
hmac := hmacSha256(data, secret)
hmacHex := hex.EncodeToString(hmac)
hmacBase64 := base64.StdEncoding.EncodeToString(hmac)
fmt.Println("HMAC-SHA256 Hex:", hmacHex)
fmt.Println("HMAC-SHA256 Base64:", hmacBase64)
}
func hmacSha256(data, secret []byte) []byte {
h := hmac.New(sha256.New, secret)
h.Write(data)
return h.Sum(nil)
}