Constant Time HMAC Compare
Compute an HMAC-SHA256 tag and compare it in constant time to avoid leaking the secret through timing.
Code
package signing
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"errors"
)
var ErrInvalidMAC = errors.New("invalid message authentication code")
func Sign(secret, message []byte) []byte {
mac := hmac.New(sha256.New, secret)
mac.Write(message)
return mac.Sum(nil)
}
func Verify(secret, message, provided []byte) error {
expected := Sign(secret, message)
if subtle.ConstantTimeCompare(expected, provided) != 1 {
return ErrInvalidMAC
}
return nil
}
func SignHex(secret, message []byte) string {
return hex.EncodeToString(Sign(secret, message))
}What the code does
Constant Time HMAC Compare reduces to the functions Sign, Verify and SignHex.
Caveats
- The dependency list is empty — the language runtime supplies everything used here.
Applying it
Signature: func Sign(secret, message []byte) []byte
Sign is the public entry point; everything else in the file exists to support it.
Statements that carry the weight
func Verify(secret, message, provided []byte) error {
expected := Sign(secret, message)
if subtle.ConstantTimeCompare(expected, provided) != 1 {
return ErrInvalidMAC
}
return nil
}
func SignHex(secret, message []byte) string {
return hex.EncodeToString(Sign(secret, message))
}
func Sign(secret, message []byte) []byte {
mac := hmac.New(sha256.New, secret)
mac.Write(message)
return mac.Sum(nil)
}
Interactive Tools for This Topic
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.TOTP URI Builder & Code GeneratorBuild valid otpauth://totp QR provisioning URIs and compute RFC 6238 HMAC-SHA1, SHA-256, or SHA-512 verification codes locally using Web Crypto.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `crypto/hmac`, `crypto/sha256`, `crypto/subtle`. The file defines `Sign`, `Verify`, `SignHex` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.