forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.go
58 lines (47 loc) · 1.16 KB
/
crypto.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
package strutil
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"fmt"
)
// Md5 Generate a 32-bit md5 string
func Md5(src any) string {
return hex.EncodeToString(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 {
h := md5.New()
switch val := src.(type) {
case []byte:
h.Write(val)
case string:
h.Write([]byte(val))
default:
h.Write([]byte(fmt.Sprint(src)))
}
return h.Sum(nil)
}
// 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))
}