-
Notifications
You must be signed in to change notification settings - Fork 15
/
func.go
118 lines (95 loc) · 1.97 KB
/
func.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
113
114
115
116
117
118
package wxpay
import (
"bytes"
"crypto/md5"
"encoding/xml"
"errors"
"fmt"
"math/rand"
"sort"
"strings"
"github.com/clbanning/mxj"
)
var (
RandChar = []byte("abcdefghijklmnopqrstuvwxyz0123456789")
RandCharLen int32 = 36
)
// makeNonceStr 生成随机字符串
func makeNonceStr(n int) string {
sb := new(strings.Builder)
for i := 0; i < n; i++ {
sb.WriteByte(RandChar[rand.Int31n(RandCharLen)])
}
return sb.String()
}
// 转化为xml数据
func toXML(param Parameter, key string) (data []byte, err error) {
err = param.Valid()
if err != nil {
return
}
data, err = xml.Marshal(param)
if err != nil {
return
}
signStr, err := makeXMLSign(data, key)
if err != nil {
return
}
param.SetSign(signStr)
data, err = xml.Marshal(param)
return
}
// checkXMLSign 校验xml数据有效性
func checkXMLSign(data []byte, key string) error {
xmlMap, err := mxj.NewMapXml(data)
if err != nil {
return err
}
dataMap, ok := xmlMap["xml"].(map[string]interface{})
if !ok {
return errors.New("非法xml")
}
signStr, ok := dataMap["sign"].(string)
if !ok {
return errors.New("无sign值")
}
sign := makeSign(dataMap, key)
if signStr != sign {
return errors.New("sign错误")
}
return nil
}
// makeXMLSign 生成xml数据的sign值
func makeXMLSign(data []byte, key string) (signStr string, err error) {
xmlMap, err := mxj.NewMapXml(data)
if err != nil {
return "", err
}
dataMap, ok := xmlMap["xml"].(map[string]interface{})
if !ok {
return "", errors.New("非法xml")
}
return makeSign(dataMap, key), nil
}
// 生成sign值
func makeSign(m map[string]interface{}, key string) string {
var keys []string
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
buf := new(bytes.Buffer)
for _, k := range keys {
if k == "sign" {
continue
}
v := fmt.Sprint(m[k])
if v == "" {
continue
}
buf.WriteString(k + "=" + v + "&")
}
buf.WriteString("key=" + key)
return fmt.Sprintf("%X", md5.Sum(buf.Bytes()))
}