forked from lilu0826/alitv_openlist
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
460 lines (393 loc) · 11.4 KB
/
main.go
File metadata and controls
460 lines (393 loc) · 11.4 KB
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/sha256"
_ "embed"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/rand"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-resty/resty/v2"
)
var client = resty.New()
//go:embed index.html
var indexHtml []byte
// 生成随机字符串iv向量(16位)
func randomString(length int) string {
if length <= 0 {
length = 32 // 默认 32
}
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
result := make([]byte, length)
// 用时间作为随机种子
rand.Seed(time.Now().UnixNano())
for i := range result {
result[i] = charset[rand.Intn(len(charset))]
}
return string(result)
}
// 计算签名
func getSign(apiPath string, t string) string {
params := GetParams(t)
key := GenerateKey(t)
// 原始数据
data := fmt.Sprintf("POST-/api%v-%v-%v-%v", apiPath, t, params["d"], key)
// 计算 SHA256
hash := sha256.Sum256([]byte(data))
// 转为十六进制字符串
hashStr := hex.EncodeToString(hash[:])
return hashStr
}
func Encrypt(plaintextStr, ivHex, keyStr string) (string, error) {
// 1. 解析 key
key := []byte(keyStr)
if len(key) != 32 {
return "", errors.New("key 长度必须为 32 字节(AES-256)")
}
// 2. 解析 IV
iv := []byte(ivHex)
if len(iv) != aes.BlockSize {
return "", errors.New("IV 长度必须为 16 字节(128 位)")
}
// 3. 转为字节并 PKCS7 padding
plaintext := []byte(plaintextStr)
plaintext = pkcs7Pad(plaintext, aes.BlockSize)
// 4. 初始化 AES-256
block, err := aes.NewCipher(key)
if err != nil {
return "", fmt.Errorf("创建 AES cipher 失败: %w", err)
}
// 5. CBC 加密
ciphertext := make([]byte, len(plaintext))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, plaintext)
// 6. Base64 编码返回
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
// PKCS7 填充
func pkcs7Pad(data []byte, blockSize int) []byte {
padding := blockSize - len(data)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(data, padText...)
}
func Decrypt(ciphertextB64, ivHex, keyStr string) (string, error) {
// 1. 解析 key(hex 转 []byte)
key := []byte(keyStr)
if len(key) != 32 {
return "", errors.New("key 长度超过 32 字节,不能用于 AES-256")
}
// 2. 解析 IV
iv, err := hex.DecodeString(ivHex)
if err != nil {
return "", fmt.Errorf("iv 解码失败: %w", err)
}
if len(iv) != aes.BlockSize {
return "", errors.New("IV 长度必须为 16 字节(128 位)")
}
// 3. 解码 base64 密文
ciphertext, err := base64.StdEncoding.DecodeString(ciphertextB64)
if err != nil {
return "", fmt.Errorf("密文 base64 解码失败: %w", err)
}
if len(ciphertext)%aes.BlockSize != 0 {
return "", errors.New("密文长度不是块大小的倍数")
}
// 4. 初始化 AES-256
block, err := aes.NewCipher(key)
if err != nil {
return "", fmt.Errorf("创建 AES cipher 失败: %w", err)
}
// 5. CBC 解密
mode := cipher.NewCBCDecrypter(block, iv)
plaintext := make([]byte, len(ciphertext))
mode.CryptBlocks(plaintext, ciphertext)
// 6. 去除 PKCS7 padding
plaintext, err = pkcs7Unpad(plaintext, aes.BlockSize)
if err != nil {
return "", fmt.Errorf("去 padding 失败: %w", err)
}
return string(plaintext), nil
}
// PKCS7 Unpadding
func pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
if len(data) == 0 || len(data)%blockSize != 0 {
return nil, errors.New("无效的数据长度")
}
padLen := int(data[len(data)-1])
if padLen == 0 || padLen > blockSize {
return nil, errors.New("无效的 padding 长度")
}
for i := len(data) - padLen; i < len(data); i++ {
if data[i] != byte(padLen) {
return nil, errors.New("padding 内容不合法")
}
}
return data[:len(data)-padLen], nil
}
func h(charArray []rune, modifier interface{}) string {
// 去重
uniqueMap := make(map[rune]bool)
var uniqueChars []rune
for _, c := range charArray {
if !uniqueMap[c] {
uniqueMap[c] = true
uniqueChars = append(uniqueChars, c)
}
}
// 处理 modifier,截取字符串后部分转换成数字
modStr := fmt.Sprintf("%v", modifier)
if len(modStr) < 7 {
panic("modifier 字符串长度不足7")
}
numPart := modStr[7:]
numericModifier, err := strconv.Atoi(numPart)
if err != nil {
panic(err)
}
var builder strings.Builder
for _, char := range uniqueChars {
charCode := int(char)
newCharCode := charCode - (numericModifier % 127) - 1
newCharCode = abs(newCharCode)
if newCharCode < 33 {
newCharCode += 33
}
builder.WriteRune(rune(newCharCode))
}
return builder.String()
}
func GetParams(t interface{}) map[string]string {
return map[string]string{
"akv": "2.8.1496", // apk_version_name 版本号
"apv": "1.4.1", // 内部版本号
"b": "vivo", // 手机品牌
"d": "2c7d30cd7ae5e8017384988393f397c6", // 设备id 可随机生成
"m": "V2329A", // 手机型号
"n": "V2329A", // 手机型号名称
"mac": "", // mac地址
"wifiMac": "00db00200063", // wifiMac地址
"nonce": "", // 随机字符串(好像没用)
"t": fmt.Sprintf("%v", t), // 时间戳
}
}
func GenerateKey(t interface{}) string {
params := GetParams(t)
// 按 key 排序
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
// 拼接除 "t" 外所有的值
var concatenatedParams strings.Builder
for _, k := range keys {
if k != "t" {
concatenatedParams.WriteString(params[k])
}
}
// 调用 h 函数
keyArray := []rune(concatenatedParams.String())
hashedKeyString := h(keyArray, t)
// MD5 加密,输出 hex
md5Sum := md5.Sum([]byte(hashedKeyString))
return hex.EncodeToString(md5Sum[:])
}
// 取绝对值
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
// 获取时间戳
func getTimestamp() string {
statusResp, err := client.R().
Get("https://api.extscreen.com/timestamp")
if err != nil || statusResp.StatusCode() != 200 {
return strconv.FormatInt(time.Now().Unix(), 10)
}
var statusData map[string]interface{}
json.Unmarshal(statusResp.Body(), &statusData)
if statusData["code"].(float64) != 200 {
return strconv.FormatInt(time.Now().Unix(), 10)
}
data := statusData["data"].(map[string]interface{})
// strconv.FormatInt((int64)data["timestamp"].(float64), 10);
return strconv.FormatInt(int64(data["timestamp"].(float64)), 10)
}
func GenerateRequestInfo(apiPath string, body map[string]interface{}) (map[string]interface{}, error) {
t := getTimestamp()
keyStr := GenerateKey(t)
headers := GetParams(t)
bodyJsonBytes, err := json.Marshal(body)
if err != nil {
fmt.Println("JSON 编码失败:", err)
return nil, err
}
bodyJsonStr := string(bodyJsonBytes)
iv := randomString(16)
encrypted, err := Encrypt(bodyJsonStr, iv, keyStr)
if err != nil {
fmt.Println("AES 加密失败:", err)
return nil, err
}
encryptedBody := map[string]interface{}{
"ciphertext": encrypted,
"iv": iv,
}
headers["Content-Type"] = "application/json"
headers["sign"] = getSign(apiPath, t)
return map[string]interface{}{
"headers": headers,
"body": encryptedBody,
"key": keyStr,
}, nil
}
// 获取二维码
func getQRCode(c *gin.Context) {
body := map[string]interface{}{
"scopes": "user:base,file:all:read,file:all:write",
"width": 500,
"height": 500,
}
requestInfo, err := GenerateRequestInfo("/v2/qrcode", body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
resp, err := client.R().
SetHeaders(requestInfo["headers"].(map[string]string)).
SetBody(requestInfo["body"].(map[string]interface{})).
Post("https://api.extscreen.com/aliyundrive/v2/qrcode")
if err != nil || resp.StatusCode() != 200 {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate QR code"})
return
}
var result map[string]interface{}
json.Unmarshal(resp.Body(), &result)
data := result["data"].(map[string]interface{})
respCiphertext := data["ciphertext"].(string)
respIv := data["iv"].(string)
plain, err := Decrypt(respCiphertext, respIv, requestInfo["key"].(string))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
var qrcodeInfo map[string]string
json.Unmarshal([]byte(plain), &qrcodeInfo)
c.JSON(http.StatusOK, gin.H{
"qr_link": qrcodeInfo["qrCodeUrl"],
"sid": qrcodeInfo["sid"],
})
}
// 检查扫码登录状态并获取 token
func checkStatus(c *gin.Context) {
sid := c.Query("sid")
if sid == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid sid"})
return
}
statusResp, err := client.R().
Get("https://openapi.alipan.com/oauth/qrcode/" + sid + "/status")
if err != nil || statusResp.StatusCode() != 200 {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to check status"})
return
}
var statusData map[string]interface{}
json.Unmarshal(statusResp.Body(), &statusData)
if statusData["status"] == "LoginSuccess" {
authCode := statusData["authCode"].(string)
handleToken(c, map[string]interface{}{"code": authCode})
return
}
c.JSON(http.StatusOK, statusData)
}
// GET /token
func getToken(c *gin.Context) {
refresh := c.Query("refresh_ui")
if refresh == "" {
c.JSON(http.StatusOK, gin.H{
"refresh_token": "",
"access_token": "",
"text": "refresh_ui parameter is required",
})
return
}
handleToken(c, map[string]interface{}{"refresh_token": refresh})
}
// POST /token
func postToken(c *gin.Context) {
var body struct {
RefreshToken string `json:"refresh_token"`
}
if err := c.ShouldBindJSON(&body); err != nil || body.RefreshToken == "" {
c.JSON(http.StatusOK, gin.H{
"refresh_token": "",
"access_token": "",
"text": "refresh_token parameter is required",
})
return
}
handleToken(c, map[string]interface{}{"refresh_token": body.RefreshToken})
}
// 获取 token
func handleToken(c *gin.Context, body map[string]interface{}) {
requestInfo, err := GenerateRequestInfo("/v4/token", body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
resp, err := client.R().
SetHeaders(requestInfo["headers"].(map[string]string)).
SetBody(requestInfo["body"].(map[string]interface{})).
Post("https://api.extscreen.com/aliyundrive/v4/token")
if err != nil || resp.StatusCode() != 200 {
c.JSON(http.StatusOK, gin.H{
"refresh_token": "",
"access_token": "",
"text": "Failed to refresh token",
})
return
}
var tokenData map[string]interface{}
json.Unmarshal(resp.Body(), &tokenData)
data := tokenData["data"].(map[string]interface{})
plain, err := Decrypt(data["ciphertext"].(string), data["iv"].(string), requestInfo["key"].(string))
if err != nil {
c.JSON(http.StatusOK, gin.H{
"refresh_token": "",
"access_token": "",
"text": err.Error(),
})
return
}
var token map[string]string
json.Unmarshal([]byte(plain), &token)
c.JSON(http.StatusOK, gin.H{
"refresh_token": token["refresh_token"],
"access_token": token["access_token"],
"text": "",
})
}
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
c.Writer.Write(indexHtml)
})
router.GET("/qr", getQRCode)
router.GET("/check", checkStatus)
router.GET("/token", getToken)
router.POST("/token", postToken)
router.Run(":8081")
}