/
md5.go
47 lines (40 loc) · 1.27 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
package hashers
import (
"crypto/md5"
"fmt"
"strings"
)
// MD5PasswordHasher is the MD5 password hasher.
type MD5PasswordHasher struct{}
// Encode encodes the given password (adding the given salt) then returns encoded.
func (p *MD5PasswordHasher) Encode(password string, salt string) string {
return fmt.Sprintf("%s%s%s%s%s",
p.Algorithm(),
HashSeparator,
salt,
HashSeparator,
fmt.Sprintf("%x", md5.Sum([]byte(salt+password))))
}
// Algorithm returns the algorithm name of this hasher.
func (p *MD5PasswordHasher) Algorithm() string {
return "md5"
}
// Verify takes the raw password and the encoded one, then checks if they match.
func (p *MD5PasswordHasher) Verify(password string, encoded string) bool {
results := strings.Split(encoded, HashSeparator)
attempt := p.Encode(password, results[1])
return encoded == attempt
}
// SafeSummary returns a summary of the encoded password.
func (p *MD5PasswordHasher) SafeSummary(encoded string) PasswordSummary {
results := strings.Split(encoded, HashSeparator)
return PasswordSummary{
Algorithm: p.Algorithm(),
Salt: results[1],
Hash: results[2],
}
}
// Salt returns the default salt (which defaults to a random 12 characters string).
func (p *MD5PasswordHasher) Salt() string {
return RandomString(12)
}