-
Notifications
You must be signed in to change notification settings - Fork 0
/
pbkdf2.go
41 lines (35 loc) · 840 Bytes
/
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
package hmacr
import "hash"
// PBKDF2 fills byte slice, p, with PBKDF2 result from password, salt and iteration count.
func PBKDF2(h func() hash.Hash, p, password, salt []byte, iter int) (int, error) {
return pbkdf2Intern(New(h, password), p, salt, iter)
}
func pbkdf2Intern(mac HMAC, p, salt []byte, iter int) (int, error) {
n := len(p)
s := mac.Size()
b := 0
// Ensure minimum of 4 bytes
tmp := make([]byte, s+4)
for i := 0; i < n; i += s {
mac.Reset()
mac.Write(salt)
b++
tmp[0] = byte(b >> 24)
tmp[1] = byte(b >> 16)
tmp[2] = byte(b >> 8)
tmp[3] = byte(b)
mac.Write(tmp[:4])
mac.Sum(tmp[:0])
nn := copy(p[i:], tmp[:s])
q := p[i : i+nn]
for j := 2; j <= iter; j++ {
mac.Reset()
mac.Write(tmp[:s])
mac.Sum(tmp[:0])
for k := 0; k < nn; k++ {
q[k] ^= tmp[k]
}
}
}
return n, nil
}