HMAC Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓HMAC Implementation runs in O(n) time and O(1) space, in Go as in every other language.
- ✓crypto/hmac plus a hash package. hmac.New(sha256.New, key) returns a hash.Hash, so you get Write, Sum and Reset from the standard interface rather than a bespoke type.
- ✓hmac.Equal, never bytes.Equal and never ==, is the one thing a reviewer will always flag. Sum(nil) is the idiomatic shape and Sum(existing) gets questioned every time.
- ✓The Go trap: Sum appends. h.Sum(b) returns b with the digest concatenated onto it and leaves the hash state untouched, which is the opposite of what the name suggests in most languages.
- ✓hmac.New allocates the wrapper plus two hash.Hash values, and because hash.Hash is an interface every Write and Sum is an indirect call the compiler cannot inline.
What HMAC Implementation actually is
HMAC Implementation in Go: what you actually reach for
Go implementation
package sig
import (
"crypto/hmac"
"crypto/sha256"
)
func Sign(key, msg []byte) []byte {
h := hmac.New(sha256.New, key)
h.Write(msg) // documented never to return an error
return h.Sum(nil) // Sum APPENDS: nil means "give me a fresh slice"
}
func Verify(key, msg, tag []byte) bool {
return hmac.Equal(Sign(key, msg), tag)
}
// Reset keeps the key, so the ipad/opad schedule is not redone per message.
func SignBatch(key []byte, msgs [][]byte) [][]byte {
h := hmac.New(sha256.New, key)
buf := make([]byte, 0, sha256.Size)
out := make([][]byte, 0, len(msgs))
for _, m := range msgs {
h.Reset()
h.Write(m)
tag := append([]byte(nil), h.Sum(buf[:0])...)
out = append(out, tag)
}
return out
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for HMAC Implementation?
crypto/hmac plus a hash package. hmac.New(sha256.New, key) returns a hash.Hash, so you get Write, Sum and Reset from the standard interface rather than a bespoke type. The comparison helper is hmac.Equal(mac1, mac2 []byte) bool, which is documented to run without leaking timing about the contents. Write never returns an error for these implementations, and Sum takes a slice to append into. Because it is a hash.Hash, an hmac value drops straight into io.MultiWriter or io.Copy for streaming a request body.
What is the most common Go mistake when implementing HMAC Implementation?
Sum appends. h.Sum(b) returns b with the digest concatenated onto it and leaves the hash state untouched, which is the opposite of what the name suggests in most languages. Two bugs follow. Passing a non-empty slice, as in h.Sum(payload), yields payload||tag and the tag you compare is offset. And since Sum does not reset, a loop that writes then Sums without Reset keeps accumulating every previous message into the same MAC, producing a tag that is stable in a single-message unit test and wrong under real traffic. Reset is the fix and it deliberately keeps the key, restoring the inner pad state rather than clearing it.
How does HMAC Implementation actually perform in Go?
hmac.New allocates the wrapper plus two hash.Hash values, and because hash.Hash is an interface every Write and Sum is an indirect call the compiler cannot inline. The implementation snapshots the keyed inner and outer states when the underlying hash can marshal itself, so Reset restores them instead of rehashing the two pad blocks: reusing one value across messages is measurably cheaper than constructing a new one. Sum(nil) allocates 32 bytes per call; handing it a reused buffer sliced to zero length only avoids that allocation when the tag does not need to outlive the iteration, since any tag you keep has to be copied out of the shared buffer anyway. On amd64 and arm64 sha256 dispatches to assembly using the CPU's SHA extensions when present. Time complexity is O(n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.