-
Notifications
You must be signed in to change notification settings - Fork 5
/
sign.go
141 lines (117 loc) · 2.48 KB
/
sign.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package wxpay
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"encoding/xml"
"fmt"
"reflect"
"sort"
"strings"
)
func checkSign(stream []byte, key string) (err error) {
defer func() {
if err != nil {
notifyAsync(string(stream), err)
}
}()
reqMap := make(map[string]string)
err = xml.Unmarshal(stream, (*Map)(&reqMap))
if err != nil {
return
}
if _, ok := reqMap["sign"]; !ok {
return
}
md5Sign := sign(reqMap, key)
if reqMap["sign"] != md5Sign {
err = signNotMatchErr
return
}
return
}
func sign(req map[string]string, key string) string {
// #1.对参数按照key=value的格式,并按照参数名ASCII字典序排序生成字符串:
sortedKeys := make([]string, 0)
for k := range req {
if k == "sign" {
continue
}
sortedKeys = append(sortedKeys, k)
}
sort.Strings(sortedKeys)
var signStrings string
for _, k := range sortedKeys {
value := req[k]
if value != "" {
signStrings += k + "=" + value + "&"
}
}
// #2.连接商户key:
signStrings = signStrings + "key=" + key
// #3.生成sign并转成大写:
hash := md5.New()
if req["sign_type"] == SignTypeSHA256 {
hash = hmac.New(sha256.New, []byte(key))
}
hash.Write([]byte(signStrings))
upperSign := strings.ToUpper(hex.EncodeToString(hash.Sum(nil)))
// #4.校验结果:
globalLogger.printf("待签名字符串: %s", signStrings)
globalLogger.printf("签名: %s", upperSign)
return upperSign
}
func signStruct(v interface{}, key string) string {
req := convert(v)
return sign(req, key)
}
func convert(str interface{}) map[string]string {
m := make(map[string]string)
val := reflect.ValueOf(str).Elem()
for i := 0; i < val.NumField(); i++ {
valueField := val.Field(i)
typeField := val.Type().Field(i)
tag := typeField.Tag.Get("xml")
list := strings.Split(tag, ",")
if len(list) == 0 {
continue
}
key := list[0]
if key == "xml" ||
key == "" ||
key == "-" {
continue
}
value := fmt.Sprintf("%v", valueField)
if strings.Contains(tag, "omitempty") {
switch valueField.Kind() {
case reflect.String:
if value == "" {
continue
}
case reflect.Int,
reflect.Int8,
reflect.Int16,
reflect.Int32,
reflect.Int64,
reflect.Uint,
reflect.Uint8,
reflect.Uint16,
reflect.Uint32,
reflect.Uint64,
reflect.Float32,
reflect.Float64:
if value == "0" {
continue
}
case reflect.Ptr:
if valueField.IsNil() {
continue
}
}
}
m[key] = value
}
return m
}