-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmd5.go
83 lines (67 loc) · 1.64 KB
/
md5.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
package password
import (
"crypto/md5" // #nosec
"encoding/hex"
"strings"
)
type md5Hasher struct {
salt string
}
func (hasher *md5Hasher) Algorithm() string {
if len(hasher.salt) > 0 {
return md5Algo
} else {
return unsaltedMd5Algo
}
}
func (hasher *md5Hasher) Encode(password string) (string, error) {
return hasher.encode(password, hasher.salt), nil
}
func (hasher *md5Hasher) encode(password, salt string) string {
h := md5.New() // #nosec
// to support `unsalted_md5`
if len(salt) > 0 {
h.Write([]byte(salt))
}
h.Write([]byte(password))
parts := []string{hasher.Algorithm(), salt, hex.EncodeToString(h.Sum(nil))}
return strings.Join(parts, sep)
}
func (hasher *md5Hasher) Decode(encoded string) (*PasswordInfo, error) {
parts := strings.SplitN(encoded, sep, 3)
if parts[0] != md5Algo && parts[0] != unsaltedMd5Algo {
return nil, errUnknownAlgorithm
}
return &PasswordInfo{
Algorithm: parts[0],
Salt: parts[1],
Hash: parts[2],
}, nil
}
func (hasher *md5Hasher) Verify(password, encoded string) bool {
pi, err := hasher.Decode(encoded)
if err != nil {
return false
}
return hasher.encode(password, pi.Salt) == encoded
}
func (hasher *md5Hasher) MustUpdate(encoded string) bool {
pi, err := hasher.Decode(encoded)
if err != nil {
return false
}
if pi.Algorithm == unsaltedMd5Algo {
return false
}
ret := mustUpdateSalt(pi.Salt, saltEntropy)
if ret {
return true
}
return len(pi.Salt) < len(hasher.salt)
}
func (hasher *md5Hasher) Harden(password, encoded string) (string, error) {
return encoded, nil
}
func newMD5Hasher(opt *HasherOption) (Hasher, error) {
return &md5Hasher{salt: opt.Salt}, nil
}