Standard library / crypto/hmac

crypto/hmac.Equal()

Compare authentication tags without content-dependent early exits for equal-length inputs. Reject different lengths and compare the expected full tag. This example uses a public test-only key. Expected stdout: 'true false\n'.

Formal Syntax & Structure

go syntaxgo
func Equal(mac1, mac2 []byte) bool

Parameters & Attributes

NameTypeDescription
mac1[]byteFirst tag.
mac2[]byteSecond tag of expected length.

Return Value

bool

True only for equal tags.

Working Example

Example Snippetgo
package main
import (  "crypto/hmac"  "crypto/sha256"  "fmt")
func main() {  h := hmac.New(sha256.New, []byte("public demo key"))  h.Write([]byte("demo"))  a := h.Sum(nil)  b := append([]byte(nil), a...)  b[0] ^= 1  fmt.Println(hmac.Equal(a, a), hmac.Equal(a, b))}
Go Reference