-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbcryptx.go
245 lines (210 loc) · 6.21 KB
/
bcryptx.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Package bcryptx automates the tuning of bcrypt costs based on an
// environment's available processing resources. Concurrency throttling is
// provided, as well as convenience functions for making use of tuned costs
// with bcrypt functions.
//
// quickCost should be used when a hash should be accessible quickly.
// strongCost should be used when the delay of processing can be mitigated.
package bcryptx
import (
"sync"
"time"
"errors"
"golang.org/x/crypto/bcrypt"
)
const (
// GenQuickMaxTime is the default max time used for tuning
// Bcrypter.quickCost.
GenQuickMaxTime = time.Millisecond * 500
// GenStrongMaxTime is the default max time used for tuning
// Bcrypter.strongCost.
GenStrongMaxTime = time.Millisecond * 2000
// GenConcurrency is the default goroutine count used for Gen*FromPass.
GenConcurrency = 2
minCost = bcrypt.MinCost
maxCost = bcrypt.MaxCost
interpTime = time.Millisecond * 50
testStr = "#!PnutBudr"
)
// Options holds values to be passed to New.
type Options struct {
// GenQuickMaxTime is the max time used for tuning Bcrypter.quickCost.
GenQuickMaxTime time.Duration
// GenStrongMaxTime is the max time used for tuning Bcrypter.strongCost.
GenStrongMaxTime time.Duration
// GenConcurrency is the goroutine count used for Gen*FromPass.
GenConcurrency int
}
// Bcrypter provides an API for bcrypt functions with "quick" or "strong" costs.
// Tune is called on first use of Gen*FromPass if not already called directly.
type Bcrypter struct {
mu *sync.RWMutex
tuningWg *sync.WaitGroup
options *Options
quickCost int
strongCost int
concCount chan bool
}
// New returns a new Bcrypter based on Options values or defaults.
func New(opts *Options) *Bcrypter {
if opts == nil {
opts = &Options{}
}
if opts.GenQuickMaxTime == 0 {
opts.GenQuickMaxTime = GenQuickMaxTime
}
if opts.GenStrongMaxTime == 0 {
opts.GenStrongMaxTime = GenStrongMaxTime
}
if opts.GenConcurrency == 0 {
opts.GenConcurrency = GenConcurrency
}
return &Bcrypter{
options: opts, mu: &sync.RWMutex{}, tuningWg: &sync.WaitGroup{},
concCount: make(chan bool, opts.GenConcurrency),
}
}
// GenQuickFromPass returns a hash produced using Bcrypter.quickCost or any
// error encountered during handling.
func (bc *Bcrypter) GenQuickFromPass(pass string) (string, error) {
bc.concCount <- true
defer func() { <-bc.concCount }()
c, err := bc.CurrentQuickCost()
if err != nil {
return "", err
}
b, err := bcrypt.GenerateFromPassword([]byte(pass), c)
return string(b), err
}
// GenStrongFromPass returns a hash produced using Bcrypter.strongCost or any
// error encountered during handling.
func (bc *Bcrypter) GenStrongFromPass(pass string) (string, error) {
bc.concCount <- true
defer func() { <-bc.concCount }()
c, err := bc.CurrentStrongCost()
if err != nil {
return "", err
}
b, err := bcrypt.GenerateFromPassword([]byte(pass), c)
return string(b), err
}
// CompareHashAndPass returns an error if comparison fails or any error
// encountered during handling.
func (bc *Bcrypter) CompareHashAndPass(hash, pass string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pass))
}
// Tune sets the quick and strong costs based on provided max times.
// Appropriate costs are determined by producing a handful of low-cost hashes,
// then using the resulting durations to interpolate the durations of hashes
// with higher costs.
func (bc *Bcrypter) Tune() error {
bc.tuningWg.Wait()
bc.tuningWg.Add(1)
return bc.tune(bc.tuningWg)
}
// IsCostQuick returns false if the apparent cost of the hash is lower than
// the provided cost, or if any errors are encountered during hash analysis.
func (bc *Bcrypter) IsCostQuick(hash string) bool {
c, err := bc.CurrentQuickCost()
if err != nil {
return false
}
return testHash(hash, c)
}
// IsCostStrong returns false if the apparent cost of the hash is lower than
// the provided cost, or if any errors are encountered during hash analysis.
func (bc *Bcrypter) IsCostStrong(hash string) bool {
c, err := bc.CurrentStrongCost()
if err != nil {
return false
}
return testHash(hash, c)
}
// ValidateHash returns an error if the provided argument is not a valid hash.
func (bc *Bcrypter) ValidateHash(hash string) error {
_, err := bcrypt.Cost([]byte(hash))
return err
}
// CurrentQuickCost returns the quickCost as set by Tune.
func (bc *Bcrypter) CurrentQuickCost() (int, error) {
bc.tuningWg.Wait()
bc.mu.RLock()
c := bc.quickCost
bc.mu.RUnlock()
if c == 0 {
if err := bc.Tune(); err != nil {
return 0, err
}
bc.mu.RLock()
c = bc.quickCost
bc.mu.RUnlock()
}
return c, nil
}
// CurrentStrongCost returns the strongCost as set by Tune.
func (bc *Bcrypter) CurrentStrongCost() (int, error) {
bc.tuningWg.Wait()
bc.mu.RLock()
c := bc.strongCost
bc.mu.RUnlock()
if c == 0 {
if err := bc.Tune(); err != nil {
return 0, err
}
bc.mu.RLock()
c = bc.strongCost
bc.mu.RUnlock()
}
return c, nil
}
// tune sets Bcrypter.quickCost and Bcrypter.strongCost, and panics on any
// error or if any cost is unable to be determined.
func (bc *Bcrypter) tune(wg *sync.WaitGroup) error {
defer wg.Done()
var qc, sc int
cts := []time.Duration{0}
for i := 1; i <= maxCost; i++ {
if i < minCost {
cts = append(cts, 0)
continue
}
if cts[i-1] < interpTime {
t1 := time.Now()
_, err := bcrypt.GenerateFromPassword([]byte(testStr), i)
d := time.Since(t1)
if err != nil {
panic("Failed to tune bcryptx: " + err.Error())
}
cts = append(cts, d)
continue
}
tct := cts[i-1] * 2
tct = tct - (tct % (time.Millisecond * 10))
cts = append(cts, tct)
}
for k := range cts {
if qc == 0 && len(cts) > k+1 && cts[k+1] > bc.options.GenQuickMaxTime {
qc = k
}
if sc == 0 && len(cts) > k+1 && cts[k+1] > bc.options.GenStrongMaxTime {
sc = k
}
}
if qc == 0 || sc == 0 {
return errors.New("Failed to tune bcryptx: hash times are too low.")
}
bc.mu.Lock()
bc.quickCost = qc
bc.strongCost = sc
bc.mu.Unlock()
return nil
}
// test returns false if the apparent cost of the hash is lower than the
// provided cost, or if any errors are encountered during hash analysis.
func testHash(hash string, cost int) bool {
c, err := bcrypt.Cost([]byte(hash))
if err != nil || c < cost {
return false
}
return true
}