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
}
}
HMAC is a way to prove that a message came from someone who knows a secret key and hasn't been tampered with. Think of it like a sealed envelope with a wax stamp; if the seal is broken or the stamp doesn't match, you know the message is compromised. You use it whenever you need to ensure data integrity and authenticity between two parties who share a secret.