forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash.go
53 lines (41 loc) · 1.18 KB
/
hash.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
package strutil
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"github.com/gookit/goutil/byteutil"
)
// Md5 Generate a 32-bit md5 string
func Md5(src any) string {
return string(Md5Bytes(src))
}
// MD5 Generate a 32-bit md5 string
func MD5(src any) string { return Md5(src) }
// GenMd5 Generate a 32-bit md5 string
func GenMd5(src any) string { return Md5(src) }
// Md5Bytes Generate a 32-bit md5 bytes
func Md5Bytes(src any) []byte {
return byteutil.Md5(src)
}
// ShortMd5 Generate a 16-bit md5 string. remove first 8 and last 8 bytes from 32-bit md5 string.
func ShortMd5(src any) string {
return string(byteutil.ShortMd5(src))
}
// HashPasswd for quick hash an input password string
func HashPasswd(pwd, key string) string {
hm := hmac.New(sha256.New, []byte(key))
hm.Write([]byte(pwd))
return hex.EncodeToString(hm.Sum(nil))
}
// VerifyPasswd for quick verify input password is valid
//
// - pwdMAC from db or config, generated by EncryptPasswd()
func VerifyPasswd(pwdMAC, pwd, key string) bool {
decBts, err := hex.DecodeString(pwdMAC)
if err != nil {
return false
}
hm := hmac.New(sha256.New, []byte(key))
hm.Write([]byte(pwd))
return hmac.Equal(decBts, hm.Sum(nil))
}