| 1 |
// Copyright 2009 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
/* |
| 6 |
Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as |
| 7 |
defined in U.S. Federal Information Processing Standards Publication 198. |
| 8 |
An HMAC is a cryptographic hash that uses a key to sign a message. |
| 9 |
The receiver verifies the hash by recomputing it using the same key. |
| 10 |
|
| 11 |
Receivers should be careful to use Equal to compare MACs in order to avoid |
| 12 |
timing side-channels: |
| 13 |
|
| 14 |
// ValidMAC reports whether messageMAC is a valid HMAC tag for message. |
| 15 |
func ValidMAC(message, messageMAC, key []byte) bool { |
| 16 |
mac := hmac.New(sha256.New, key) |
| 17 |
mac.Write(message) |
| 18 |
expectedMAC := mac.Sum(nil) |
| 19 |
return hmac.Equal(messageMAC, expectedMAC) |
| 20 |
} |
| 21 |
*/ |
| 22 |
package hmac |
| 23 |
|
| 24 |
import ( |
| 25 |
"crypto/internal/boring" |
| 26 |
"crypto/internal/fips140/hmac" |
| 27 |
"crypto/internal/fips140hash" |
| 28 |
"crypto/internal/fips140only" |
| 29 |
"crypto/subtle" |
| 30 |
"hash" |
| 31 |
) |
| 32 |
|
| 33 |
// New returns a new HMAC hash using the given [hash.Hash] type and key. |
| 34 |
// New functions like [crypto/sha256.New] can be used as h. |
| 35 |
// h must return a new Hash every time it is called. |
| 36 |
// Note that unlike other hash implementations in the standard library, |
| 37 |
// the returned Hash does not implement [encoding.BinaryMarshaler] |
| 38 |
// or [encoding.BinaryUnmarshaler]. |
| 39 |
func New(h func() hash.Hash, key []byte) hash.Hash { |
| 40 |
if boring.Enabled { |
| 41 |
hm := boring.NewHMAC(h, key) |
| 42 |
if hm != nil { |
| 43 |
return hm |
| 44 |
} |
| 45 |
// BoringCrypto did not recognize h, so fall through to standard Go code. |
| 46 |
} |
| 47 |
h = fips140hash.UnwrapNew(h) |
| 48 |
if fips140only.Enforced() { |
| 49 |
if len(key) < 112/8 { |
| 50 |
panic("crypto/hmac: use of keys shorter than 112 bits is not allowed in FIPS 140-only mode") |
| 51 |
} |
| 52 |
if !fips140only.ApprovedHash(h()) { |
| 53 |
panic("crypto/hmac: use of hash functions other than SHA-2 or SHA-3 is not allowed in FIPS 140-only mode") |
| 54 |
} |
| 55 |
} |
| 56 |
return hmac.New(h, key) |
| 57 |
} |
| 58 |
|
| 59 |
// Equal compares two MACs for equality without leaking timing information. |
| 60 |
func Equal(mac1, mac2 []byte) bool { |
| 61 |
// We don't have to be constant time if the lengths of the MACs are |
| 62 |
// different as that suggests that a completely different hash function |
| 63 |
// was used. |
| 64 |
return subtle.ConstantTimeCompare(mac1, mac2) == 1 |
| 65 |
} |