forked from objcoding/wxpay
-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
96 lines (79 loc) · 1.67 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
86
87
88
89
90
91
92
93
94
95
96
package wxpay
import (
"bytes"
"crypto/tls"
"encoding/pem"
"encoding/xml"
"log"
"regexp"
"strconv"
"strings"
"time"
"golang.org/x/crypto/pkcs12"
)
var re *regexp.Regexp = regexp.MustCompile(`>\n\s*`)
func XmlToMap(xmlStr string) Params {
xmlStr = re.ReplaceAllString(xmlStr, ">")
params := make(Params)
decoder := xml.NewDecoder(strings.NewReader(xmlStr))
var (
key string
value string
)
for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
switch token := t.(type) {
case xml.StartElement: // 开始标签
key = token.Name.Local
case xml.CharData: // 标签内容
content := string([]byte(token))
value = content
}
if key != "xml" {
if value != "\n" {
params.SetString(key, value)
}
}
}
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
}