-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.crypto.go
112 lines (100 loc) · 2.28 KB
/
util.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package util
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"fmt"
"io"
)
// MD5 返回binary结果
func MD5(src string) (rst []byte) {
h := md5.New()
io.WriteString(h, src)
rst = h.Sum(nil)
return
}
// MD5 返回 hex结果
func MD5String(src string) (rst string) {
rst = fmt.Sprintf("%x", MD5(src))
return
}
// MD5 返回 hex结果大写
func MD5StringX(src string) (rst string) {
rst = fmt.Sprintf("%X", MD5(src))
return
}
// AES 返回binary结果
func AES(byteKey, src []byte, isEncode bool) (rst []byte) {
rst = make([]byte, len(src))
c, err := aes.NewCipher(byteKey)
if err != nil {
return
}
if isEncode {
c.Encrypt(rst, src)
} else {
c.Decrypt(rst, src)
}
return
}
// AES 返回 hex结果
func AESString(byteKey, src []byte, isEncode bool) (rst string) {
dst := AES(byteKey, src, isEncode)
rst = fmt.Sprintf("%x", dst)
return
}
// AES 返回 hex结果大写
func AESStringX(byteKey, src []byte, isEncode bool) (rst string) {
dst := AES(byteKey, src, isEncode)
rst = fmt.Sprintf("%X", dst)
return
}
// AES-CBC 返回binary结果
func AESCBC(byteKey, src []byte, isEncode bool) (rst []byte) {
rst = make([]byte, len(src))
b, err := aes.NewCipher(byteKey)
if err != nil {
return
}
iv := byteKey[:aes.BlockSize]
var cc cipher.BlockMode
var nsrc []byte
if isEncode {
cc = cipher.NewCBCEncrypter(b, iv)
nsrc = PKCS5Padding(src, aes.BlockSize)
} else {
cc = cipher.NewCBCDecrypter(b, iv)
nsrc = src
}
dst := make([]byte, len(nsrc))
cc.CryptBlocks(dst, nsrc)
if isEncode {
rst = dst
} else {
rst = PKCS5UnPadding(dst)
}
return
}
// AES-CBC 返回 hex结果
func AESCBCString(byteKey, src []byte, isEncode bool) (rst string) {
dst := AESCBC(byteKey, src, isEncode)
rst = fmt.Sprintf("%x", dst)
return
}
// AES-CBC 返回 hex结果大写
func AESCBCStringX(byteKey, src []byte, isEncode bool) (rst string) {
dst := AESCBC(byteKey, src, isEncode)
rst = fmt.Sprintf("%X", dst)
return
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}