/
verify.go
68 lines (57 loc) · 2.67 KB
/
verify.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
package pbkdf
import (
"crypto"
"fmt"
)
// VerifyPasswordPBKDF1 checks if a password matches an encoded password
// The encoded password must be in the format: salt:iterationCount:hashedPassword(salt and hashedPassword are base64 encoded)
// The hash parameter is the hash function to be used(can be any crypto.Hash)
// The password parameter is the password to be checked
// The encodedPassword parameter is the encoded password
func VerifyPasswordPBKDF1(hash crypto.Hash, password, encodedPassword string) (bool, error) {
return VerifyPassword(hash, password, encodedPassword, PBKDF1)
}
// VerifyPasswordPBKDF2 checks if a password matches an encoded password
// The encoded password must be in the format: salt:iterationCount:hashedPassword(salt and hashedPassword are base64 encoded)
// The hash parameter is the hash function to be used(can be any crypto.Hash)
// The password parameter is the password to be checked
// The encodedPassword parameter is the encoded password
func VerifyPasswordPBKDF2(hash crypto.Hash, password, encodedPassword string) (bool, error) {
return VerifyPassword(hash, password, encodedPassword, PBKDF2)
}
// VerifyPassword checks if a password matches an encoded password
// The encoded password must be in the format: salt:iterationCount:hashedPassword(salt and hashedPassword are base64 encoded)
// The hash parameter is the hash function to be used(can be any crypto.Hash)
// The password parameter is the password to be checked
// The encodedPassword parameter is the encoded password
// The function parameter is the function that has been used to generate the encoded password
// it must have the PBKDF signature
func VerifyPassword(hash crypto.Hash, password, encodedPassword string, kdf PBKDF) (bool, error) {
// get the password parameters
saltAsBytes, iterationCount, passwordHash, err := GetPasswordParametersFromString(encodedPassword)
// check if an error occurred
if err != nil {
return false, fmt.Errorf("error in VerifyPassword kdf while getting password parameters: %s", err.Error())
}
// transform the password into a byte slice
passwordAsBytes := []byte(password)
// encode the password
passwordHash2, err := kdf(hash, passwordAsBytes, saltAsBytes, iterationCount, int64(len(passwordHash)))
// check if an error occurred
if err != nil {
return false, fmt.Errorf("error in VerifyPassword kdf while encoding password: %s", err.Error())
}
// check if the hashes have same length
if len(passwordHash) != len(passwordHash2) {
return false, nil
}
// check if the hashes are equal
for i, v := range passwordHash {
if v != passwordHash2[i] {
// bytes are not equal, return false
return false, nil
}
}
// return true
return true, nil
}