/
password.go
92 lines (76 loc) · 1.69 KB
/
password.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
package passwordtool
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"strings"
)
// Errors
var (
ErrInvalidHash = errors.New("passwordtool: invalid hash password")
ErrMismatched = errors.New("passwordtool: hashed and password mismatched")
)
var strategies = []HashComparer{
Argon2id{},
PBKDF2{},
Scrypt{},
BcryptHash{},
Bcrypt{},
}
// HashComparer interface
type HashComparer interface {
fmt.Stringer
Hash(password string) (string, error)
Compare(hashedPassword string, password string) error
}
var defaultStrategy = Argon2id{}
// Hash hashes password using default strategy
func Hash(password string) (string, error) {
return defaultStrategy.Hash(password)
}
// Compare compares hashed and password
// returns nil if hashed and password equal
func Compare(hashedPassword string, password string) error {
hc := findHC(hashedPassword)
if hc == nil {
return ErrInvalidHash
}
return hc.Compare(hashedPassword, password)
}
func findHC(hashedPassword string) HashComparer {
if len(hashedPassword) == 0 {
return nil
}
for _, s := range strategies {
if strings.HasPrefix(hashedPassword, s.String()+"$") {
return s
}
}
return nil
}
func extract(hashedPassword string) (strategy string, hashed string) {
if len(hashedPassword) == 0 {
return
}
ps := strings.SplitN(hashedPassword, "$", 2)
if len(ps) != 2 {
return
}
return ps[0], ps[1]
}
func generateSalt(s int) ([]byte, error) {
p := make([]byte, s)
_, err := rand.Read(p)
if err != nil {
return nil, err
}
return p, nil
}
func encodeBase64(p []byte) string {
return base64.RawStdEncoding.EncodeToString(p)
}
func decodeBase64(s string) []byte {
p, _ := base64.RawStdEncoding.DecodeString(s)
return p
}