-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathsignature.go
279 lines (230 loc) · 5.44 KB
/
signature.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package sdk
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"
"github.com/clbanning/mxj"
)
// Signature :
type Signature struct {
SignType string
Sign string
NonceStr string
Timestamp string
Data string
}
var signTypeMapper = map[string]crypto.Hash{
SHA256: crypto.SHA256,
}
// GenerateDataBase64 :
func GenerateDataBase64(jsonData []byte) (string, error) {
bodyBuffer := new(bytes.Buffer)
if jsonData != nil {
m, err := mxj.NewMapJson(jsonData)
sortJSON, err := m.Json(true)
if err = json.Compact(bodyBuffer, sortJSON); err != nil {
return "", err
}
}
bodyStr := strings.TrimSpace(bodyBuffer.String())
bodyByte := bodyBuffer.Bytes()
base64Body := ""
switch bodyStr {
case "{}":
case "null":
default:
base64Body = base64.StdEncoding.EncodeToString(bodyByte)
}
return base64Body, nil
}
func (c *Client) generateSignature(data interface{}, method, requestURL string) (*Signature, error) {
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
bodyBuffer := new(bytes.Buffer)
if data != nil {
m, err := mxj.NewMapJson(jsonData)
sortJSON, err := m.Json(true)
if err = json.Compact(bodyBuffer, sortJSON); err != nil {
return nil, err
}
}
bodyStr := strings.TrimSpace(bodyBuffer.String())
bodyByte := bodyBuffer.Bytes()
base64Body := ""
switch bodyStr {
case "{}":
case "null":
default:
base64Body = base64.StdEncoding.EncodeToString(bodyByte)
}
return Generate(
strconv.FormatInt(int64(time.Now().UTC().Unix()), 10),
randomString(32),
method,
requestURL,
c.SignType,
base64Body,
c.PrivateKey,
)
}
// Generate :
func Generate(timestamp, nonceStr, method, requestURL, signType, body string, privateKey []byte) (*Signature, error) {
method = strings.ToLower(method)
h, isExist := signTypeMapper[signType]
if !isExist {
return nil, errors.New("sign type not found")
}
data, err := formData(timestamp, nonceStr, method, requestURL, signType, body)
if err != nil {
return nil, err
}
signature, err := rsa2Hash(h, []byte(data), privateKey)
if err != nil {
return nil, err
}
return &Signature{
SignType: signType,
Sign: fmt.Sprintf("%s %s", signType, signature),
NonceStr: nonceStr,
Timestamp: timestamp,
Data: data,
}, nil
}
// Validate :
func Validate(timestamp, nonceStr, method, requestURL, signature, base64Body string, publicKey []byte) bool {
method = strings.ToLower(method)
signArr := strings.Split(signature, " ")
if len(signArr) != 2 {
return false
}
signType := signArr[0]
signature = signArr[1]
h, isExist := signTypeMapper[signType]
if !isExist {
return false
}
data, err := formData(timestamp, nonceStr, method, requestURL, signType, base64Body)
if err != nil {
return false
}
if err := verifyPKCS1v15(h, publicKey, []byte(data), signature); err != nil {
return false
}
return true
}
type signForm struct {
Data string `json:"data,omitempty"`
Method string `json:"method"`
NonceStr string `json:"nonceStr"`
RequestURL string `json:"requestUrl"`
SignType string `json:"signType"`
Timestamp string `json:"timestamp"`
}
func formData(timestamp, nonceStr, method, requestURL, signType, body string) (string, error) {
s := signForm{
Data: body,
Timestamp: timestamp,
NonceStr: nonceStr,
Method: method,
RequestURL: requestURL,
SignType: signType,
}
jsonData, err := json.Marshal(s)
if err != nil {
return "", err
}
data, err := sortJSONByKey(jsonData)
if err != nil {
return "", err
}
return data, nil
}
func rsa2Hash(h crypto.Hash, data, privateKey []byte) (string, error) {
signature, err := signPKCS1v15(h, data, privateKey)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(signature), nil
}
func signPKCS1v15(hash crypto.Hash, src, key []byte) ([]byte, error) {
var h = hash.New()
if _, err := h.Write(src); err != nil {
return nil, err
}
hashed := h.Sum(nil)
block, _ := pem.Decode(key)
if block == nil {
return nil, errors.New("private key error")
}
pk, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return rsa.SignPKCS1v15(rand.Reader, pk, hash, hashed)
}
func verifyPKCS1v15(ch crypto.Hash, publicKey []byte, data []byte, signature string) error {
var hashed []byte
switch ch {
case crypto.SHA256:
var h = sha256.New()
h.Write(data)
hashed = h.Sum(nil)
}
block, _ := pem.Decode(publicKey)
if block == nil {
return errors.New("public key error")
}
var pubInterface interface{}
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return err
}
var pub = pubInterface.(*rsa.PublicKey)
signByte, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return err
}
return rsa.VerifyPKCS1v15(pub, crypto.SHA256, hashed, signByte)
}
func sortJSONByKey(b []byte) (string, error) {
m, err := mxj.NewMapJson(b)
if err != nil {
return "", err
}
m = m.Old()
arr := make([]string, 0)
for k, v := range m {
if strings.TrimSpace(strings.ToLower(k)) == "sign" {
continue
}
str := ""
switch vi := v.(type) {
case map[string]interface{}:
continue
case string:
if vi == "" || vi == "{}" {
continue
}
str = vi
default:
str = fmt.Sprintf("%v", vi)
}
arr = append(arr, fmt.Sprintf("%s=%s", k, str))
}
sort.Sort(sort.StringSlice(arr))
return strings.Join(arr, "&"), nil
}