-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcrypto.go
96 lines (89 loc) · 1.63 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
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
93
94
95
96
package gutil
import (
"crypto/aes"
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"fmt"
)
// AESEncryptData
func AESEncryptData(keystr, src string) (string, error) {
key := []byte(keystr)
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
bs := block.BlockSize()
d := []byte(src)
d = padData(d, bs)
r := make([]byte, len(d))
r1 := r
for len(d) > 0 {
block.Encrypt(r1, d)
d = d[bs:]
r1 = r1[bs:]
}
s := hex.EncodeToString(r)
return s, err
}
// AESDecryptData
func AESDecryptData(keystr, hexSrc string) (string, error) {
key := []byte(keystr)
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
src, err := hex.DecodeString(hexSrc)
if err != nil {
return "", err
}
bs := block.BlockSize()
d := []byte(src)
r := make([]byte, len(d))
r1 := r
for len(d) > 0 {
block.Decrypt(r1, d)
d = d[bs:]
r1 = r1[bs:]
}
return string(removePad(r)), nil
}
// removePad
func removePad(r []byte) []byte {
l := len(r)
last := int(r[l-1])
pad := r[l-last : l]
isPad := true
for _, v := range pad {
if int(v) != last {
isPad = false
break
}
}
if !isPad {
return r
}
return r[:l-last]
}
// padData
func padData(d []byte, bs int) []byte {
padedSize := ((len(d) / bs) + 1) * bs
pad := padedSize - len(d)
for i := len(d); i < padedSize; i++ {
d = append(d, byte(pad))
}
return d
}
// HmacSHA1
func HmacSHA1(key string, data string) string {
mac := hmac.New(sha1.New, []byte(key))
mac.Write([]byte(data))
return hex.EncodeToString(mac.Sum(nil))
}
// Sha256
func Sha256(s string) string {
h := sha256.New()
h.Write([]byte(s))
return fmt.Sprintf("%x", h.Sum(nil))
}