Debian Codegraph @

bcrypt/bcrypt.go

raw symbols SCIP
1 // Copyright 2011 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 // Package bcrypt implements Provos and Mazières's bcrypt adaptive hashing
6 // algorithm. See http://www.usenix.org/event/usenix99/provos/provos.pdf
7 package bcrypt
8
9 // The code is a port of Provos and Mazières's C implementation.
10 import (
11 "crypto/rand"
12 "crypto/subtle"
13 "fmt"
14 "io"
15 "strconv"
16
17 "github.com/go-crypt/x/blowfish"
18 )
19
20 type hashed struct {
21 hash []byte
22 salt []byte
23 cost int // allowed range is MinCost to MaxCost
24 major byte
25 minor byte
26 }
27
28 // GenerateFromPassword returns the bcrypt hash of the password at the given
29 // cost. If the cost given is less than MinCost, the cost will be set to
30 // DefaultCost, instead. Use CompareHashAndPassword, as defined in this package,
31 // to compare the returned hashed password with its cleartext version.
32 func GenerateFromPassword(password []byte, cost int) ([]byte, error) {
33 p, err := newFromPassword(password, cost)
34 if err != nil {
35 return nil, err
36 }
37 return p.Hash(), nil
38 }
39
40 // GenerateFromPasswordSalt returns the bcrypt hash of the password at the given
41 // cost. If the cost given is less than MinCost, the cost will be set to
42 // DefaultCost, instead. Use CompareHashAndPassword, as defined in this package,
43 // to compare the returned hashed password with its cleartext version.
44 func GenerateFromPasswordSalt(password, salt []byte, cost int) ([]byte, error) {
45 p, err := newFromPasswordSalt(password, salt, cost)
46 if err != nil {
47 return nil, err
48 }
49 return p.Hash(), nil
50 }
51
52 // Key returns a new key from password/salt combination. Salt must be 16 bytes. For storage the salt needs to be encoded
53 // with bcrypt.Base64Encode.
54 func Key(password, salt []byte, cost int) ([]byte, error) {
55 p, err := newFromPasswordSalt(password, salt, cost)
56 if err != nil {
57 return nil, err
58 }
59 return p.Key(), nil
60 }
61
62 // CompareHashAndPassword compares a bcrypt hashed password with its possible
63 // plaintext equivalent. Returns nil on success, or an error on failure.
64 func CompareHashAndPassword(hashedPassword, password []byte) error {
65 p, err := newFromHash(hashedPassword)
66 if err != nil {
67 return err
68 }
69
70 otherHash, err := bcrypt(password, p.cost, p.salt)
71 if err != nil {
72 return err
73 }
74
75 otherP := &hashed{otherHash, p.salt, p.cost, p.major, p.minor}
76 if subtle.ConstantTimeCompare(p.Hash(), otherP.Hash()) == 1 {
77 return nil
78 }
79
80 return ErrMismatchedHashAndPassword
81 }
82
83 // Cost returns the hashing cost used to create the given hashed
84 // password. When, in the future, the hashing cost of a password system needs
85 // to be increased in order to adjust for greater computational power, this
86 // function allows one to establish which passwords need to be updated.
87 func Cost(hashedPassword []byte) (int, error) {
88 p, _, err := newFromHashPartial(hashedPassword)
89 if err != nil {
90 return 0, err
91 }
92
93 return p.cost, nil
94 }
95
96 // NewSalt generates a salt with an appropriate length.
97 func NewSalt() (salt []byte, err error) {
98 salt = make([]byte, maxSaltSize)
99 _, err = io.ReadFull(rand.Reader, salt)
100
101 return salt, err
102 }
103
104 func newFromPasswordSalt(password, salt []byte, cost int) (p *hashed, err error) {
105 if cost < MinCost {
106 cost = DefaultCost
107 }
108 p = new(hashed)
109 p.major = majorVersion
110 p.minor = minorVersion
111
112 if err = checkSalt(salt); err != nil {
113 return nil, err
114 }
115 p.salt = Base64Encode(salt)
116
117 if err = checkCost(cost); err != nil {
118 return nil, err
119 }
120 p.cost = cost
121
122 hash, err := bcrypt(password, p.cost, p.salt)
123 if err != nil {
124 return nil, err
125 }
126 p.hash = hash
127 return p, err
128 }
129
130 func newFromPassword(password []byte, cost int) (p *hashed, err error) {
131 var salt []byte
132
133 if salt, err = NewSalt(); err != nil {
134 return nil, err
135 }
136
137 return newFromPasswordSalt(password, salt, cost)
138 }
139
140 func newFromHashPartial(hashedSecret []byte) (p *hashed, secret []byte, err error) {
141 if len(hashedSecret) < minHashSize {
142 return nil, nil, ErrHashTooShort
143 }
144
145 p = new(hashed)
146
147 n, err := p.decodeVersion(hashedSecret)
148 if err != nil {
149 return nil, nil, err
150 }
151
152 hashedSecret = hashedSecret[n:]
153
154 n, err = p.decodeCost(hashedSecret)
155 if err != nil {
156 return nil, nil, err
157 }
158
159 hashedSecret = hashedSecret[n:]
160
161 return p, hashedSecret, nil
162 }
163
164 func newFromHash(hashedSecret []byte) (*hashed, error) {
165 p, hashedSecret, err := newFromHashPartial(hashedSecret)
166 if err != nil {
167 return nil, err
168 }
169
170 if len(hashedSecret) != EncodedSaltSize+EncodedHashSize {
171 return nil, ErrSecretInvalidLength
172 }
173
174 p.salt, p.hash = DecodeSecret(hashedSecret)
175
176 return p, nil
177 }
178
179 // DecodeSecret decodes a valid bcrypt secret into a salt and key. This function will panic if the secret does not have
180 // the len of EncodedSaltSize + EncodedHashSize.
181 func DecodeSecret(secret []byte) (salt, key []byte) {
182 if len(secret) != EncodedSaltSize+EncodedHashSize {
183 panic("secret is malformed as it does not have the expected size")
184 }
185
186 salt, key = make([]byte, EncodedSaltSize, EncodedSaltSize), make([]byte, EncodedHashSize, EncodedHashSize)
187
188 copy(salt, secret[:EncodedSaltSize])
189 copy(key, secret[EncodedSaltSize:])
190
191 return
192 }
193
194 func bcrypt(password []byte, cost int, salt []byte) ([]byte, error) {
195 cipherData := make([]byte, len(magicCipherData))
196 copy(cipherData, magicCipherData)
197
198 c, err := expensiveBlowfishSetup(password, uint32(cost), salt)
199 if err != nil {
200 return nil, err
201 }
202
203 for i := 0; i < 24; i += 8 {
204 for j := 0; j < 64; j++ {
205 c.Encrypt(cipherData[i:i+8], cipherData[i:i+8])
206 }
207 }
208
209 // Bug compatibility with C bcrypt implementations. We only encode 23 of
210 // the 24 bytes encrypted.
211 hsh := Base64Encode(cipherData[:maxCryptedHashSize])
212 return hsh, nil
213 }
214
215 func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, error) {
216 csalt, err := Base64Decode(salt)
217 if err != nil {
218 return nil, err
219 }
220
221 // Bug compatibility with C bcrypt implementations. They use the trailing
222 // NULL in the key string during expansion.
223 // We copy the key to prevent changing the underlying array.
224 ckey := append(key[:len(key):len(key)], 0)
225
226 c, err := blowfish.NewSaltedCipher(ckey, csalt)
227 if err != nil {
228 return nil, err
229 }
230
231 var i, rounds uint64
232 rounds = 1 << cost
233 for i = 0; i < rounds; i++ {
234 blowfish.ExpandKey(ckey, c)
235 blowfish.ExpandKey(csalt, c)
236 }
237
238 return c, nil
239 }
240
241 func (p *hashed) Key() []byte {
242 return p.hash
243 }
244
245 func (p *hashed) Hash() []byte {
246 arr := make([]byte, 60)
247 arr[0] = '$'
248 arr[1] = p.major
249 n := 2
250 if p.minor != 0 {
251 arr[2] = p.minor
252 n = 3
253 }
254 arr[n] = '$'
255 n++
256 copy(arr[n:], fmt.Sprintf("%02d", p.cost))
257 n += 2
258 arr[n] = '$'
259 n++
260 copy(arr[n:], p.salt)
261 n += EncodedSaltSize
262 copy(arr[n:], p.hash)
263 n += EncodedHashSize
264 return arr[:n]
265 }
266
267 func (p *hashed) decodeVersion(sbytes []byte) (int, error) {
268 if sbytes[0] != '$' {
269 return -1, InvalidHashPrefixError(sbytes[0])
270 }
271 if sbytes[1] > majorVersion {
272 return -1, HashVersionTooNewError(sbytes[1])
273 }
274 p.major = sbytes[1]
275 n := 3
276 if sbytes[2] != '$' {
277 p.minor = sbytes[2]
278 n++
279 }
280 return n, nil
281 }
282
283 // sbytes should begin where decodeVersion left off.
284 func (p *hashed) decodeCost(sbytes []byte) (int, error) {
285 cost, err := strconv.Atoi(string(sbytes[0:2]))
286 if err != nil {
287 return -1, err
288 }
289 err = checkCost(cost)
290 if err != nil {
291 return -1, err
292 }
293 p.cost = cost
294 return 3, nil
295 }
296
297 func (p *hashed) String() string {
298 return fmt.Sprintf("&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}", string(p.hash), p.salt, p.cost, p.major, p.minor)
299 }
300
301 func checkSalt(salt []byte) error {
302 if len(salt) != maxSaltSize {
303 return InvalidSaltSizeError{salt}
304 }
305
306 return nil
307 }
308
309 func checkCost(cost int) error {
310 if cost < MinCost || cost > MaxCost {
311 return InvalidCostError(cost)
312 }
313 return nil
314 }