/
tls-sig-api.go
225 lines (206 loc) · 5.71 KB
/
tls-sig-api.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
package TLSSigAPI
import (
"bytes"
"compress/zlib"
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"encoding/asn1"
"encoding/base64"
"encoding/json"
"errors"
"io/ioutil"
"math/big"
"strconv"
"time"
)
var (
ErrorIdentifierNotMatch = errors.New("identifier not match")
ErrorAppidNotMatch = errors.New("appid not match")
ErrorExpired = errors.New("expired")
ErrorInvalidSignature = errors.New("invalid signature")
signArray = []string{
"TLS.appid_at_3rd",
"TLS.account_type",
"TLS.identifier",
"TLS.sdk_appid",
"TLS.time",
"TLS.expire_after",
}
signUserbufArray = []string{
"TLS.appid_at_3rd",
"TLS.account_type",
"TLS.identifier",
"TLS.sdk_appid",
"TLS.time",
"TLS.expire_after",
"TLS.userbuf",
}
)
type ecdsaSignature struct {
R, S *big.Int
}
func generateSignContent(obj map[string]string) string {
var buffer bytes.Buffer
for _, key := range signArray {
buffer.WriteString(key)
buffer.WriteString(":")
buffer.WriteString(obj[key])
buffer.WriteString("\n")
}
return buffer.String()
}
func generateSignContentWithUserbuf(obj map[string]string) string {
var buffer bytes.Buffer
for _, key := range signUserbufArray {
buffer.WriteString(key)
buffer.WriteString(":")
buffer.WriteString(obj[key])
buffer.WriteString("\n")
}
return buffer.String()
}
func sign(key *ecdsa.PrivateKey, raw string) (string, error) {
hash := sha256.Sum256([]byte(raw))
r, s, err := ecdsa.Sign(rand.Reader, key, hash[:])
if err != nil {
return "", err
}
sig, err := asn1.Marshal(ecdsaSignature{r, s})
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(sig), nil
}
func verify(text string, sign string, key *ecdsa.PublicKey) error {
sig, err := base64.StdEncoding.DecodeString(sign)
if err != nil {
return err
}
var s ecdsaSignature
_, err = asn1.Unmarshal(sig, &s)
if err != nil {
return err
}
hash := sha256.Sum256([]byte(text))
if ecdsa.Verify(key, hash[:], s.R, s.S) {
return nil
} else {
return ErrorInvalidSignature
}
}
func compressAndBase64Encode(data []byte) string {
var b bytes.Buffer
w := zlib.NewWriter(&b)
w.Write(data)
w.Close()
return base64urlEncode(b.Bytes())
}
func base64DecodeAndUncompress(data string) ([]byte, error) {
raw, err := base64urlDecode(data)
if err != nil {
return nil, err
}
r, err := zlib.NewReader(bytes.NewReader(raw))
if err != nil {
return nil, err
}
return ioutil.ReadAll(r)
}
func generateSig(privateKey string, obj map[string]string, genRawMethod func(map[string]string) string) (string, error) {
key, err := readPrivateKey(privateKey)
if err != nil {
return "", err
}
raw := genRawMethod(obj)
signature, err := sign(key, raw)
if err != nil {
return "", err
}
obj["TLS.sig"] = signature
text, err := json.Marshal(obj)
if err != nil {
return "", err
}
return compressAndBase64Encode(text), nil
}
func GenerateUsersigWithExpire(privateKey string, appid int, identifier string, expire int64) (string, error) {
obj := map[string]string{
"TLS.account_type": "0",
"TLS.identifier": "" + identifier,
"TLS.appid_at_3rd": "0",
"TLS.sdk_appid": strconv.Itoa(appid),
"TLS.expire_after": strconv.FormatInt(expire, 10),
"TLS.version": "201610110000",
"TLS.time": strconv.FormatInt(time.Now().Unix(), 10),
}
return generateSig(privateKey, obj, generateSignContent)
}
func GenerateUsersig(privateKey string, appid int, identifier string) (string, error) {
return GenerateUsersigWithExpire(privateKey, appid, identifier, 60*60*24*180)
}
func genSig(sdkappid int, identifier string, priKey string) (string, error) {
return GenerateUsersigWithExpire(priKey, sdkappid, identifier, 60*60*24*180)
}
func GenerateUsersigWithUserbuf(privateKey string, appid int, identifier string, expire int64, userbuf []byte) (string, error) {
obj := map[string]string{
"TLS.account_type": "0",
"TLS.identifier": "" + identifier,
"TLS.appid_at_3rd": "0",
"TLS.sdk_appid": strconv.Itoa(appid),
"TLS.expire_after": strconv.FormatInt(expire, 10),
"TLS.version": "201610110000",
"TLS.time": strconv.FormatInt(time.Now().Unix(), 10),
"TLS.userbuf": base64.StdEncoding.EncodeToString(userbuf),
}
return generateSig(privateKey, obj, generateSignContentWithUserbuf)
}
func readAndVerifyUserSig(userSig string, appid int, identifier string, publicKey string, genRawMethod func(map[string]string) string) (map[string]string, error) {
text, err := base64DecodeAndUncompress(userSig)
if err != nil {
return nil, err
}
obj := make(map[string]string)
err = json.Unmarshal(text, &obj)
if err != nil {
return nil, err
}
if obj["TLS.identifier"] != identifier {
return nil, ErrorIdentifierNotMatch
}
if obj["TLS.sdk_appid"] != strconv.Itoa(appid) {
return nil, ErrorAppidNotMatch
}
createTime, err := strconv.ParseInt(obj["TLS.time"], 10, 64)
if err != nil {
return nil, err
}
expire, err := strconv.ParseInt(obj["TLS.expire_after"], 10, 64)
if err != nil {
return nil, err
}
if createTime+expire < time.Now().Unix() {
return nil, ErrorExpired
}
key, err := readPublicKey(publicKey)
if err != nil {
return nil, err
}
content := genRawMethod(obj)
err = verify(content, obj["TLS.sig"], key)
if err != nil {
return nil, err
}
return obj, nil
}
func VerifyUsersig(publicKey string, usersig string, appid int, identifier string) error {
_, err := readAndVerifyUserSig(usersig, appid, identifier, publicKey, generateSignContent)
return err
}
func VerifyUsersigWithUserbuf(publicKey string, usersig string, appid int, identifier string) ([]byte, error) {
obj, err := readAndVerifyUserSig(usersig, appid, identifier, publicKey, generateSignContentWithUserbuf)
if err != nil {
return nil, err
}
return base64.StdEncoding.DecodeString(obj["TLS.userbuf"])
}