pass

Paddy 2014-11-19 Parent:b394d1d58b85 Child:7304f24504cf

1:22ce15152c43 Go to Latest

pass/pass.go

Fix a bug with salt generation. Our salt generation had a logic bug that would bail out in the absence of an error and continue on in the presence of an error, which is exactly the opposite of the behaviour we want. Basically, typo.

History
1 package pass
3 import (
4 "crypto/rand"
5 "crypto/subtle"
6 "hash"
7 "time"
9 "code.google.com/p/go.crypto/pbkdf2"
10 )
12 func Create(h func() hash.Hash, iters int, passphrase []byte) (result, salt []byte, err error) {
13 salt = make([]byte, 32)
14 _, err = rand.Read(salt)
15 if err != nil {
16 return []byte{}, []byte{}, err
17 }
18 result = Check(h, iters, passphrase, salt)
19 return result, salt, err
20 }
22 func CalculateIterations(h func() hash.Hash) (int, error) {
23 hashInstance := h()
24 salt := make([]byte, 32)
25 _, err := rand.Read(salt)
26 if err != nil {
27 return 0, err
28 }
29 iter := 2048
30 var duration time.Duration
31 for duration < time.Second {
32 iter = iter * 2
33 timeStart := time.Now()
34 pbkdf2.Key([]byte("password1"), salt, iter, hashInstance.Size(), h)
35 duration = time.Since(timeStart)
36 }
37 return iter, nil
38 }
40 func Check(h func() hash.Hash, iters int, passphrase, salt []byte) []byte {
41 hashInstance := h()
42 return pbkdf2.Key(passphrase, salt, iters, hashInstance.Size(), h)
43 }
45 func Compare(candidate, expectation []byte) bool {
46 candidateConsistent := make([]byte, len(candidate))
47 expectationConsistent := make([]byte, len(candidate))
48 subtle.ConstantTimeCopy(1, candidateConsistent, candidate)
49 subtle.ConstantTimeCopy(1, expectationConsistent, expectation)
50 return subtle.ConstantTimeCompare(candidateConsistent, expectationConsistent) == 1
51 }