pass
2015-12-14
Parent:22ce15152c43
pass/pass.go
Update to new crypto import path. Our the Go crypto library is now located at golang.org/x/crypto, so we need to update to use that instead of Google Code.
1 package pass
3 import (
4 "crypto/rand"
5 "crypto/subtle"
6 "hash"
7 "time"
9 "golang.org/x/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 }