crypto/hmac

Guided tour · Crypto · pkg.go.dev →

Keyed Message Authentication Code. Pair with any Hash (SHA-256 usually) to authenticate messages.

Sign and verify

Sign

mac := hmac.New(sha256.New, []byte("secret"))
mac.Write([]byte("message"))
sig := mac.Sum(nil)
fmt.Printf("%x\n", sig)

Verify — use hmac.Equal, not bytes.Equal

hmac.Equal is constant-time. Plain comparison leaks timing info that attackers can exploit.

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

if !hmac.Equal(provided, expected) {
    return errors.New("bad signature")
}

Common uses

Cookie signing, API signed URLs (AWS-style), webhook signatures (GitHub, Stripe), JWT HS256.