forked from corestoreio/pkg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hashpool.go
183 lines (164 loc) · 4.7 KB
/
hashpool.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// Copyright 2015-present, Cyrill @ Schumacher.fm and the CoreStore contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hashpool
import (
"crypto/subtle"
"encoding/hex"
"hash"
"io"
"sync"
"github.com/corestoreio/errors"
"github.com/corestoreio/pkg/util/bufferpool"
)
// Hash64Mock allows to use a hash.Hash as an argument to the Hash64 Tank.
type Hash64Mock struct {
hash.Hash
}
// Sum64 returns always zero.
func (d Hash64Mock) Sum64() uint64 {
return 0
}
// Tank implements a sync.Pool for hash.Hash
type Tank struct {
p *sync.Pool
// BufferSize used in SumBase64() to append the hashed data to. Default 1024.
BufferSize int
}
// Get returns type safe a hash.
func (t Tank) Get() hash.Hash64 {
return t.p.Get().(hash.Hash64)
}
// Sum calculates the hash of data and appends the current hash to appendTo and
// returns the resulting slice. It does not change the underlying hash state. It
// fetches a hash from the pool and returns it after writing the sum. No need to
// call Get() and Put().
func (t Tank) Sum(data, appendTo []byte) (ret []byte) {
h := t.Get()
_, _ = h.Write(data)
ret = h.Sum(appendTo)
t.Put(h)
return ret
}
// SumHex writes the hashed data into the hex encoder.
func (t Tank) SumHex(data []byte) string {
buf := bufferpool.Get()
bs := 1024
if t.BufferSize > 0 {
bs = t.BufferSize
}
buf.Grow(bs)
tmpBuf := t.Sum(data, buf.Bytes())
buf.Reset()
_, _ = buf.Write(tmpBuf)
ret := hex.EncodeToString(buf.Bytes())
bufferpool.Put(buf)
return ret
}
// Equal hashes data and compares it with MAC for equality without leaking
// timing information.
func (t Tank) Equal(data []byte, mac []byte) bool {
buf := bufferpool.Get()
defer bufferpool.Put(buf)
// We don't have to be constant time if the lengths of the MACs are
// different as that suggests that a completely different hash function
// was used.
return subtle.ConstantTimeCompare(t.Sum(data, buf.Bytes()), mac) == 1
}
// EqualPairs compares data pairs for equality via constant time. Returns true
// only if all pairs are equal and one data item length is at least greater than
// zero. Use case: Compare username and password from database with a username
// and password from an outside input form.
func (t Tank) EqualPairs(dataPairs ...[]byte) bool {
ldp := len(dataPairs)
if ldp == 0 || ldp%2 == 1 {
return false
}
twinBuf := bufferpool.GetTwin()
defer bufferpool.PutTwin(twinBuf)
eq := 0
for i := 0; i <= ldp/2; i = i + 2 {
if len(dataPairs[i]) == 0 {
return false
}
if subtle.ConstantTimeCompare(t.Sum(dataPairs[i], twinBuf.First.Bytes()), t.Sum(dataPairs[i+1], twinBuf.Second.Bytes())) == 1 {
eq++
}
twinBuf.Reset()
}
return eq == ldp/2
}
// EqualReader hashes io.Reader and compares it with MAC for equality without
// leaking timing information. The internal buffer to read into data from
// io.Reader can be adjusted via field BufferSize.
func (t Tank) EqualReader(r io.Reader, mac []byte) (bool, error) {
h := t.Get()
defer t.Put(h)
bs := 4096
if t.BufferSize > 0 {
bs = t.BufferSize
}
buf := make([]byte, bs)
for {
n, err := r.Read(buf)
if err == io.EOF {
break
}
if err != nil {
return false, errors.Wrap(err, "[hashpool] r.Read")
}
if _, err := h.Write(buf[:n]); err != nil {
return false, errors.Wrap(err, "[hashpool] Hash.Write")
}
}
// We don't have to be constant time if the lengths of the MACs are
// different as that suggests that a completely different hash function
// was used.
return subtle.ConstantTimeCompare(h.Sum(buf[:0]), mac) == 1, nil
}
// Put empties the hash and returns it back to the pool.
//
// hp := New(fnv.New64)
// hsh := hp.Get()
// defer hp.Put(hsh)
// // your code
// return hsh.Sum([]byte{})
//
func (t Tank) Put(h hash.Hash64) {
h.Reset()
t.p.Put(h)
}
// New64 instantiates a new hash pool with a custom pre-allocated hash.Hash64.
func New64(h func() hash.Hash64) Tank {
return Tank{
p: &sync.Pool{
New: func() interface{} {
nh := h()
nh.Reset()
return nh
},
},
}
}
// New instantiates a new hash pool with a custom pre-allocated hash.Hash.
func New(h func() hash.Hash) Tank {
return Tank{
p: &sync.Pool{
New: func() interface{} {
nh := h()
nh.Reset()
return Hash64Mock{Hash: nh}
},
},
}
}