-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwxcrypto.go
More file actions
102 lines (95 loc) · 2.27 KB
/
Copy pathwxcrypto.go
File metadata and controls
102 lines (95 loc) · 2.27 KB
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
package wxcrypto
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/binary"
"errors"
"io"
)
var (
ErrAppIdInvalid = errors.New("appid不匹配")
)
type WxCrypto struct {
token string
appid string
aesKey []byte
iv []byte
}
// 实例化
func New(token, appid, encodingAESKey string) (*WxCrypto, error) {
aesKey, err := base64.StdEncoding.DecodeString(encodingAESKey + "=")
if err != nil {
return nil, err
}
return &WxCrypto{
token: token,
appid: appid,
aesKey: aesKey,
iv: aesKey[:16],
}, nil
}
// 加密 data为要加密的XML字符串转换后的字节数组
func (p *WxCrypto) Encrypt(data []byte) ([]byte, error) {
var (
random16 = make([]byte, 16)
msgLength = int32(len(data))
appid = []byte(p.appid)
err error
)
// 写入随机数
if _, err := io.ReadFull(rand.Reader, random16); err != nil {
return nil, err
}
// 写入消息体
buf := new(bytes.Buffer)
err = binary.Write(buf, binary.BigEndian, &random16)
err = binary.Write(buf, binary.BigEndian, &msgLength)
err = binary.Write(buf, binary.BigEndian, &data)
err = binary.Write(buf, binary.BigEndian, &appid)
if err != nil {
return nil, err
}
data = buf.Bytes()
data = PKCS7Encode(data, 32)
// 开始加密
block, err := aes.NewCipher(p.aesKey)
if err != nil {
return nil, err
}
mode := cipher.NewCBCEncrypter(block, p.iv)
cipherData := make([]byte, len(data))
mode.CryptBlocks(cipherData, data)
return cipherData, nil
}
// 解密 data为微信传输过来的XML消息体Encrypt字段base64解码后的字节数组
func (p *WxCrypto) Decrypt(data []byte) ([]byte, error) {
block, err := aes.NewCipher(p.aesKey)
if err != nil {
return nil, err
}
mode := cipher.NewCBCDecrypter(block, p.iv)
mode.CryptBlocks(data, data)
data = PKCS7Decode(data)
// 去除随机的16字节
data = data[16:]
// 解码消息
var (
msgLength int32
reader = bytes.NewReader(data)
)
err = binary.Read(reader, binary.BigEndian, &msgLength)
msg := make([]byte, int(msgLength))
err = binary.Read(reader, binary.BigEndian, &msg)
appid := make([]byte, len(p.appid))
err = binary.Read(reader, binary.BigEndian, &appid)
if err != nil {
return nil, err
}
if string(appid) != p.appid {
return nil, ErrAppIdInvalid
}
return msg, nil
}