-
-
Notifications
You must be signed in to change notification settings - Fork 105
/
hash_comparator.go
200 lines (167 loc) · 5.52 KB
/
hash_comparator.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
package hasherx
import (
"context"
"crypto/subtle"
"encoding/base64"
"fmt"
"regexp"
"strings"
"github.com/pkg/errors"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt"
"golang.org/x/crypto/pbkdf2"
)
var ErrUnknownHashAlgorithm = errors.New("unknown hash algorithm")
// Compare the given password with the given hash.
func Compare(ctx context.Context, password []byte, hash []byte) error {
switch {
case IsBcryptHash(hash):
return CompareBcrypt(ctx, password, hash)
case IsArgon2idHash(hash):
return CompareArgon2id(ctx, password, hash)
case IsArgon2iHash(hash):
return CompareArgon2i(ctx, password, hash)
case IsPbkdf2Hash(hash):
return ComparePbkdf2(ctx, password, hash)
default:
return errors.WithStack(ErrUnknownHashAlgorithm)
}
}
func CompareBcrypt(_ context.Context, password []byte, hash []byte) error {
if err := validateBcryptPasswordLength(password); err != nil {
return err
}
err := bcrypt.CompareHashAndPassword(hash, password)
if err != nil {
return err
}
return nil
}
func CompareArgon2id(_ context.Context, password []byte, hash []byte) error {
// Extract the parameters, salt and derived key from the encoded password
// hash.
p, salt, hash, err := decodeArgon2idHash(string(hash))
if err != nil {
return err
}
// Derive the key from the other password using the same parameters.
otherHash := argon2.IDKey([]byte(password), salt, p.Iterations, uint32(p.Memory), p.Parallelism, p.KeyLength)
// Check that the contents of the hashed passwords are identical. Note
// that we are using the subtle.ConstantTimeCompare() function for this
// to help prevent timing attacks.
if subtle.ConstantTimeCompare(hash, otherHash) == 1 {
return nil
}
return errors.WithStack(ErrMismatchedHashAndPassword)
}
func CompareArgon2i(_ context.Context, password []byte, hash []byte) error {
// Extract the parameters, salt and derived key from the encoded password
// hash.
p, salt, hash, err := decodeArgon2idHash(string(hash))
if err != nil {
return err
}
// Derive the key from the other password using the same parameters.
otherHash := argon2.Key([]byte(password), salt, p.Iterations, uint32(p.Memory), p.Parallelism, p.KeyLength)
// Check that the contents of the hashed passwords are identical. Note
// that we are using the subtle.ConstantTimeCompare() function for this
// to help prevent timing attacks.
if subtle.ConstantTimeCompare(hash, otherHash) == 1 {
return nil
}
return errors.WithStack(ErrMismatchedHashAndPassword)
}
func ComparePbkdf2(_ context.Context, password []byte, hash []byte) error {
// Extract the parameters, salt and derived key from the encoded password
// hash.
p, salt, hash, err := decodePbkdf2Hash(string(hash))
if err != nil {
return err
}
// Derive the key from the other password using the same parameters.
otherHash := pbkdf2.Key(password, salt, int(p.Iterations), int(p.KeyLength), getPseudorandomFunctionForPbkdf2(p.Algorithm))
// Check that the contents of the hashed passwords are identical. Note
// that we are using the subtle.ConstantTimeCompare() function for this
// to help prevent timing attacks.
if subtle.ConstantTimeCompare(hash, otherHash) == 1 {
return nil
}
return errors.WithStack(ErrMismatchedHashAndPassword)
}
var (
isBcryptHash = regexp.MustCompile(`^\$2[abzy]?\$`)
isArgon2idHash = regexp.MustCompile(`^\$argon2id\$`)
isArgon2iHash = regexp.MustCompile(`^\$argon2i\$`)
isPbkdf2Hash = regexp.MustCompile(`^\$pbkdf2-sha[0-9]{1,3}\$`)
)
func IsBcryptHash(hash []byte) bool {
return isBcryptHash.Match(hash)
}
func IsArgon2idHash(hash []byte) bool {
return isArgon2idHash.Match(hash)
}
func IsArgon2iHash(hash []byte) bool {
return isArgon2iHash.Match(hash)
}
func IsPbkdf2Hash(hash []byte) bool {
return isPbkdf2Hash.Match(hash)
}
func decodeArgon2idHash(encodedHash string) (p *Argon2Config, salt, hash []byte, err error) {
parts := strings.Split(encodedHash, "$")
if len(parts) != 6 {
return nil, nil, nil, ErrInvalidHash
}
var version int
_, err = fmt.Sscanf(parts[2], "v=%d", &version)
if err != nil {
return nil, nil, nil, err
}
if version != argon2.Version {
return nil, nil, nil, ErrIncompatibleVersion
}
p = new(Argon2Config)
_, err = fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Iterations, &p.Parallelism)
if err != nil {
return nil, nil, nil, err
}
salt, err = base64.RawStdEncoding.Strict().DecodeString(parts[4])
if err != nil {
return nil, nil, nil, err
}
p.SaltLength = uint32(len(salt))
hash, err = base64.RawStdEncoding.Strict().DecodeString(parts[5])
if err != nil {
return nil, nil, nil, err
}
p.KeyLength = uint32(len(hash))
return p, salt, hash, nil
}
// decodePbkdf2Hash decodes PBKDF2 encoded password hash.
// format: $pbkdf2-<digest>$i=<iterations>,l=<length>$<salt>$<hash>
func decodePbkdf2Hash(encodedHash string) (p *PBKDF2Config, salt, hash []byte, err error) {
parts := strings.Split(encodedHash, "$")
if len(parts) != 5 {
return nil, nil, nil, ErrInvalidHash
}
p = new(PBKDF2Config)
digestParts := strings.SplitN(parts[1], "-", 2)
if len(digestParts) != 2 {
return nil, nil, nil, ErrInvalidHash
}
p.Algorithm = digestParts[1]
_, err = fmt.Sscanf(parts[2], "i=%d,l=%d", &p.Iterations, &p.KeyLength)
if err != nil {
return nil, nil, nil, err
}
salt, err = base64.RawStdEncoding.Strict().DecodeString(parts[3])
if err != nil {
return nil, nil, nil, err
}
p.SaltLength = uint32(len(salt))
hash, err = base64.RawStdEncoding.Strict().DecodeString(parts[4])
if err != nil {
return nil, nil, nil, err
}
p.KeyLength = uint32(len(hash))
return p, salt, hash, nil
}