hmac.New, hash.Hash.Write, hash.Hash.Sum
func New(h func() hash.Hash, key []byte) hash.HashCompute an HMAC-SHA256 tag of a message under a key.
| Parameter | Description |
|---|---|
h | A function that returns a new hash.Hash, such as sha256.New. |
key | The HMAC key. The example uses the fixed public bytes example-hmac-key-not-for-production, which are not a production secret. |
Returns: A hash.Hash. After Write of the message, Sum(nil) returns the MAC tag as a slice.
- The printed digest is the HMAC-SHA256 of "hello" under that sample key, measured on Go 1.24.0.
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
)
func main() {
key := []byte("example-hmac-key-not-for-production")
msg := []byte("hello")
mac := hmac.New(sha256.New, key)
mac.Write(msg)
fmt.Println(hex.EncodeToString(mac.Sum(nil)))
}Expected output
d2a29298c27f3cf3b9aef19fe4ca1eae102be02c274a9dae5d2ded58c6697220Related: crypto/sha256