Constant Time HMAC Compare

Compute an HMAC-SHA256 tag and compare it in constant time to avoid leaking the secret through timing.

GoSecurity Boundaries

Code

gosnippet
29 lines
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

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.