/
pbkdf2.go
132 lines (113 loc) · 2.26 KB
/
pbkdf2.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
package passwordtool
import (
"crypto/subtle"
"fmt"
"strconv"
"strings"
"golang.org/x/crypto/pbkdf2"
)
const (
pbkdf2DefaultIter = 10000
pbkdf2DefaultKeyLen = 32
pbkdf2DefaultS = 8
)
var pbkdf2DefaultH = SHA512
// PBKDF2 strategy
type PBKDF2 struct {
Iter int
KeyLen int
S int
H Hasher
}
func (PBKDF2) String() string {
return "pbkdf2"
}
func (hc PBKDF2) iter() int {
if hc.Iter <= 0 {
return pbkdf2DefaultIter
}
return hc.Iter
}
func (hc PBKDF2) keyLen() int {
if hc.KeyLen <= 0 {
return pbkdf2DefaultKeyLen
}
return hc.KeyLen
}
func (hc PBKDF2) s() int {
if hc.S <= 0 {
return pbkdf2DefaultS
}
return hc.S
}
func (hc PBKDF2) h() Hasher {
if hc.H == nil {
return pbkdf2DefaultH
}
return hc.H
}
func (hc PBKDF2) hash(password string) (string, error) {
salt, err := generateSalt(hc.s())
if err != nil {
return "", err
}
h, iter, keyLen := hc.h(), hc.iter(), hc.keyLen()
dk := pbkdf2.Key([]byte(password), salt, iter, keyLen, h.New)
return fmt.Sprintf(
"%s$%d$%d$%s$%s",
h, iter, keyLen,
encodeBase64(salt), encodeBase64(dk),
), nil
}
func (hc PBKDF2) compare(hashed, password string) error {
h, iter, keyLen, salt, dk := hc.decode(hashed)
if h == nil {
return ErrInvalidHash
}
if len(dk) == 0 {
return ErrInvalidHash
}
pk := pbkdf2.Key([]byte(password), salt, iter, keyLen, h.New)
if subtle.ConstantTimeCompare(dk, pk) == 1 {
return nil
}
return ErrMismatched
}
func (hc PBKDF2) decode(hashed string) (h Hasher, iter, keyLen int, salt, dk []byte) {
xs := strings.Split(hashed, "$")
if len(xs) != 5 {
return
}
h = findHasher(xs[0])
if h == nil {
return
}
var err error
iter, err = strconv.Atoi(xs[1])
if err != nil {
return
}
keyLen, err = strconv.Atoi(xs[2])
if err != nil {
return
}
salt = decodeBase64(xs[3])
dk = decodeBase64(xs[4])
return
}
// Hash hashes password
func (hc PBKDF2) Hash(password string) (string, error) {
hashed, err := hc.hash(password)
if err != nil {
return "", err
}
return hc.String() + "$" + string(hashed), nil
}
// Compare compares hashed with password
func (hc PBKDF2) Compare(hashedPassword string, password string) error {
s, hashed := extract(hashedPassword)
if s != hc.String() {
return ErrInvalidHash
}
return hc.compare(hashed, password)
}