-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
66 lines (57 loc) · 1.38 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
package webhook
import (
"encoding/xml"
"errors"
"strconv"
"github.com/aimuz/wgo/xcrypto"
)
// WXBizMsgCryptor ...
type WXBizMsgCryptor interface {
DecryptMessage(payload []byte, v interface{}) error
EncryptMessage(payload []byte, timestamp int64, nonce string) ([]byte, error)
}
// WXBizMsgCrypto ...
type WXBizMsgCrypto struct {
appID string
token string
crypto xcrypto.Crypto
}
// NewWXBizMsgCrypto ...
func NewWXBizMsgCrypto(encodingAESKey, appID, token string) (*WXBizMsgCrypto, error) {
c, err := xcrypto.NewWXCrypto(encodingAESKey, appID)
if err != nil {
return nil, err
}
return &WXBizMsgCrypto{
appID: appID,
token: token,
crypto: c,
}, nil
}
// DecryptMessage ...
func (wc *WXBizMsgCrypto) DecryptMessage(payload []byte, v interface{}) error {
if wc.crypto == nil {
return errors.New("crypto: wc.crypto not init")
}
// decrypt payload
payload, err := wc.crypto.Decrypt(payload)
if err != nil {
return err
}
err = xml.Unmarshal(payload, v)
if err != nil {
return err
}
return nil
}
// EncryptMessage ...
func (wc *WXBizMsgCrypto) EncryptMessage(payload []byte, timestamp int64, nonce string) ([]byte, error) {
sign := SHA1Sign(strconv.FormatInt(timestamp, 10), wc.token, nonce, string(payload))
msg := &EncryptMessage{
Encrypt: string(payload),
MsgSignature: sign,
TimeStamp: timestamp,
Nonce: nonce,
}
return xml.Marshal(msg)
}