-
Notifications
You must be signed in to change notification settings - Fork 3
/
signature.go
73 lines (63 loc) · 1.28 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
package paymentwall
import (
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"fmt"
"hash"
"reflect"
"sort"
)
func sortKeys(arr interface{}) []string {
v := reflect.ValueOf(arr)
if v.Kind() != reflect.Map {
return make([]string, 0)
}
allKeys := reflect.ValueOf(arr).MapKeys()
keys := make([]string, len(allKeys))
for _, v := range allKeys {
k := v.String()
if len(k) > 0 {
keys = append(keys, k)
}
}
sort.Strings(keys)
return keys
}
func prepareParameters(data map[string]interface{}, baseString string) string {
base := ""
keys := sortKeys(data)
for _, key := range keys {
value := data[key]
switch t := value.(type) {
case nil:
continue
case map[string]string:
ks := sortKeys(t)
for _, k := range ks {
if len(k) == 0 {
continue
}
v := t[k]
base += key + "[" + k + "]" + "=" + v
}
default:
base += key + "=" + fmt.Sprint(t)
}
}
return base + baseString
}
func CalculateSignature(privateKey string, data map[string]interface{}, version int) string {
str := prepareParameters(data, privateKey)
var hasher hash.Hash
switch version {
case 1, 2:
hasher = md5.New()
case 3:
hasher = sha256.New()
default:
panic("invalid signature version")
}
hasher.Write([]byte(str))
return hex.EncodeToString(hasher.Sum(nil))
}