-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecrypt.go
70 lines (55 loc) · 1.45 KB
/
decrypt.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
package swan_miniprogram
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/json"
"errors"
)
func Decrypt(encryptedData, sessionKey, iv, appKey string) (userinfo Userinfo, err error) {
key, err := base64.StdEncoding.DecodeString(sessionKey)
if err != nil {
return
}
ivBytes, err := base64.StdEncoding.DecodeString(iv)
if err != nil {
return
}
encryptedDataBytess, err := base64.StdEncoding.DecodeString(encryptedData)
if err != nil {
return
}
var block cipher.Block
if block, err = aes.NewCipher([]byte(key)); err != nil {
return
}
if len(encryptedData) < aes.BlockSize {
err = errors.New("encryptedData too short")
}
cbc := cipher.NewCBCDecrypter(block, ivBytes)
cbc.CryptBlocks(encryptedDataBytess, encryptedDataBytess)
encryptedDataBytess = pKCS7UnPadding(encryptedDataBytess)
if len(encryptedDataBytess) < 20 {
err = errors.New("bad content")
return
}
// 前面16位可以直接抛弃,17-20表示明文长度
// TODO
size := encryptedDataBytess[19]
if len(encryptedDataBytess) < 20+int(size) {
err = errors.New("bad content")
return
}
// 最后N位一定是appKey
if string(encryptedDataBytess[size+20:]) != appKey {
err = errors.New("illegal appKey")
return
}
err = json.Unmarshal(encryptedDataBytess[20:size+20], &userinfo)
return
}
func pKCS7UnPadding(plantText []byte) []byte {
length := len(plantText)
unPadding := int(plantText[length-1])
return plantText[:(length - unPadding)]
}