How to Use HMAC for Message Authentication in Go

Generate and verify message authentication codes in Go using the crypto/hmac package with a secure hash function like SHA-256.

Use the crypto/hmac package with a hash function like crypto/sha256 to generate a keyed-hash message authentication code. Create an HMAC instance with your secret key, write the message bytes to it, and retrieve the resulting digest.

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

func generateHMAC(key, message []byte) []byte {
	h := hmac.New(sha256.New, key)
	h.Write(message)
	return h.Sum(nil)
}

To verify a message, generate the HMAC again and compare it with the received digest using hmac.Equal to prevent timing attacks.