How do I sign and verify data with HMAC in Go?

In Go, HMAC (Hash-based Message Authentication Code) is used for both signing and verifying data. HMAC combines a secret key with a hash function to ensure data integrity and authenticity. Below is a simple example of how to implement HMAC in Go.

package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" ) func main() { secretKey := []byte("your-secret-key") message := []byte("message to be signed") // Signing the message h := hmac.New(sha256.New, secretKey) h.Write(message) signature := h.Sum(nil) // Convert signature to hexadecimal string signatureHex := hex.EncodeToString(signature) fmt.Printf("Signature: %s\n", signatureHex) // Verifying the message isValid := verifyHMAC(message, secretKey, signature) if isValid { fmt.Println("Message is valid.") } else { fmt.Println("Message is invalid.") } } func verifyHMAC(message, secretKey, signature []byte) bool { h := hmac.New(sha256.New, secretKey) h.Write(message) expectedSignature := h.Sum(nil) return hmac.Equal(expectedSignature, signature) }

HMAC Go data signing data verification hashing Go programming cryptography