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.
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.
11 Receivers should be careful to use Equal to compare MACs in order to avoid
14 // CheckMAC reports whether messageMAC is a valid HMAC tag for message.
15 func CheckMAC(message, messageMAC, key []byte) bool {
16 mac := hmac.New(sha256.New, key)
18 expectedMAC := mac.Sum(nil)
19 return hmac.Equal(messageMAC, expectedMAC)
30 // http://csrc.nist.gov/publications/fips/fips198-1/FIPS-198-1_final.pdf
32 // key is zero padded to the block size of the hash function
33 // ipad = 0x36 byte repeated for key length
34 // opad = 0x5c byte repeated for key length
35 // hmac = H([key ^ opad] H([key ^ ipad] text))
41 outer
, inner hash
.Hash
44 func (h
*hmac
) Sum(in
[]byte) []byte {
49 h
.outer
.Write(in
[origLen
:])
50 return h
.outer
.Sum(in
[:origLen
])
53 func (h
*hmac
) Write(p
[]byte) (n
int, err error
) {
54 return h
.inner
.Write(p
)
57 func (h
*hmac
) Size() int { return h
.size
}
59 func (h
*hmac
) BlockSize() int { return h
.blocksize
}
61 func (h
*hmac
) Reset() {
66 // New returns a new HMAC hash using the given hash.Hash type and key.
67 // Note that unlike other hash implementations in the standard library,
68 // the returned Hash does not implement encoding.BinaryMarshaler
69 // or encoding.BinaryUnmarshaler.
70 func New(h
func() hash
.Hash
, key
[]byte) hash
.Hash
{
74 hm
.size
= hm
.inner
.Size()
75 hm
.blocksize
= hm
.inner
.BlockSize()
76 hm
.ipad
= make([]byte, hm
.blocksize
)
77 hm
.opad
= make([]byte, hm
.blocksize
)
78 if len(key
) > hm
.blocksize
{
79 // If key is too big, hash it.
81 key
= hm
.outer
.Sum(nil)
85 for i
:= range hm
.ipad
{
88 for i
:= range hm
.opad
{
91 hm
.inner
.Write(hm
.ipad
)
95 // Equal compares two MACs for equality without leaking timing information.
96 func Equal(mac1
, mac2
[]byte) bool {
97 // We don't have to be constant time if the lengths of the MACs are
98 // different as that suggests that a completely different hash function
100 return subtle
.ConstantTimeCompare(mac1
, mac2
) == 1