forked from objcoding/wxpay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
85 lines (73 loc) · 1.45 KB
/
util.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
package wxpay
import (
"bytes"
"crypto/tls"
"encoding/pem"
"encoding/xml"
"golang.org/x/crypto/pkcs12"
"log"
"strconv"
"strings"
"time"
)
func XmlToMap(xmlStr string) Params {
params := make(Params)
d := xml.NewDecoder(strings.NewReader(xmlStr))
var start *xml.StartElement
for {
tok, err := d.Token()
if err != nil {
break
}
switch t := tok.(type) {
case xml.StartElement:
start = &t
case xml.CharData:
if t = bytes.TrimSpace(t); len(t) > 0 {
params.SetString(start.Name.Local, string(t))
}
}
}
return params
}
func MapToXml(params Params) string {
var buf bytes.Buffer
buf.WriteString(`<xml>`)
for k, v := range params {
buf.WriteString(`<`)
buf.WriteString(k)
buf.WriteString(`><![CDATA[`)
buf.WriteString(v)
buf.WriteString(`]]></`)
buf.WriteString(k)
buf.WriteString(`>`)
}
buf.WriteString(`</xml>`)
return buf.String()
}
// 用时间戳生成随机字符串
func nonceStr() string {
return strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
}
// 将Pkcs12转成Pem
func pkcs12ToPem(p12 []byte, password string) tls.Certificate {
blocks, err := pkcs12.ToPEM(p12, password)
// 从恐慌恢复
defer func() {
if x := recover(); x != nil {
log.Print(x)
}
}()
if err != nil {
panic(err)
}
var pemData []byte
for _, b := range blocks {
pemData = append(pemData, pem.EncodeToMemory(b)...)
}
cert, err := tls.X509KeyPair(pemData, pemData)
if err != nil {
panic(err)
}
return cert
}