How to Use HMAC in Go

Compute an HMAC in Go by importing crypto/hmac and crypto/sha256, creating a new HMAC instance with your key, writing your message, and calling Sum to get the result.

Use the crypto/hmac package with a hash function like crypto/sha256 to compute a keyed-hash message authentication code.

package main

import (
	"crypto/hmac"
	"crypto/sha256"
)

func main() {
	key := []byte("secret-key")
	message := []byte("data-to-authenticate")

	h := hmac.New(sha256.New, key)
	h.Write(message)
	mac := h.Sum(nil)

	// Verify
	if !hmac.Equal(mac, h.Sum(nil)) {
		// mismatch
	}
}