1
2
3
4
5
6
7
8
9 package hmac
10
11 import (
12 "crypto/md5"
13 "crypto/sha1"
14 "crypto/sha256"
15 "hash"
16 "os"
17 )
18
19
20
21
22
23
24
25
26
27 const (
28
29
30
31
32
33
34 padSize = 64
35 )
36
37 type hmac struct {
38 size int
39 key, tmp []byte
40 outer, inner hash.Hash
41 }
42
43 func (h *hmac) tmpPad(xor byte) {
44 for i, k := range h.key {
45 h.tmp[i] = xor ^ k
46 }
47 for i := len(h.key); i < padSize; i++ {
48 h.tmp[i] = xor
49 }
50 }
51
52 func (h *hmac) Sum() []byte {
53 sum := h.inner.Sum()
54 h.tmpPad(0x5c)
55 for i, b := range sum {
56 h.tmp[padSize+i] = b
57 }
58 h.outer.Reset()
59 h.outer.Write(h.tmp)
60 return h.outer.Sum()
61 }
62
63 func (h *hmac) Write(p []byte) (n int, err os.Error) {
64 return h.inner.Write(p)
65 }
66
67 func (h *hmac) Size() int { return h.size }
68
69 func (h *hmac) Reset() {
70 h.inner.Reset()
71 h.tmpPad(0x36)
72 h.inner.Write(h.tmp[0:padSize])
73 }
74
75
76 func New(h func() hash.Hash, key []byte) hash.Hash {
77 hm := new(hmac)
78 hm.outer = h()
79 hm.inner = h()
80 hm.size = hm.inner.Size()
81 hm.tmp = make([]byte, padSize+hm.size)
82 if len(key) > padSize {
83
84 hm.outer.Write(key)
85 key = hm.outer.Sum()
86 }
87 hm.key = make([]byte, len(key))
88 copy(hm.key, key)
89 hm.Reset()
90 return hm
91 }
92
93
94 func NewMD5(key []byte) hash.Hash { return New(md5.New, key) }
95
96
97 func NewSHA1(key []byte) hash.Hash { return New(sha1.New, key) }
98
99
100 func NewSHA256(key []byte) hash.Hash { return New(sha256.New, key) }