/
security.go
50 lines (42 loc) · 1.01 KB
/
security.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
package werkzeug
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
"golang.org/x/crypto/pbkdf2"
)
const (
Method = "pbkdf2:sha256"
SaltLength = 8
Iterations = 150000
)
const (
satlChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
keyLength = 32
)
func GeneratePasswordHash(password string) string {
salt := genSalt()
hash := hashString(salt, password)
return fmt.Sprintf("%s:%v$%s$%s", Method, Iterations, salt, hash)
}
func CheckPasswordHash(password string, hash string) bool {
if strings.Count(hash, "$") < 2 {
return false
}
ps := strings.Split(hash, "$")
return ps[2] == hashString(ps[1], password)
}
func genSalt() string {
var bytes = make([]byte, SaltLength)
rand.Read(bytes)
for k, v := range bytes {
bytes[k] = satlChars[v%byte(len(satlChars))]
}
return string(bytes)
}
func hashString(salt string, password string) string {
hash := pbkdf2.Key([]byte(password), []byte(salt), Iterations, keyLength, sha256.New)
return hex.EncodeToString(hash)
}