forked from lightningminers/go-dingtalk
/
crypto.go
142 lines (132 loc) · 3.95 KB
/
crypto.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
package dingtalk
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/binary"
"errors"
r "math/rand"
"sort"
"strings"
"time"
)
type DingTalkCrypto struct {
Token string
EncodingAESKey string
SuiteKey string
BKey []byte
Block cipher.Block
}
func NewDingTalkCrypto(token, encodingAESKey, suiteKey string) *DingTalkCrypto {
if len(encodingAESKey) != aesEncodeKeyLen {
panic("不合法的EncodingAESKey")
}
bkey, err := base64.StdEncoding.DecodeString(encodingAESKey + "=")
if err != nil {
panic(err.Error())
}
block, err := aes.NewCipher(bkey)
if err != nil {
panic(err.Error())
}
c := &DingTalkCrypto{
Token: token,
EncodingAESKey: encodingAESKey,
SuiteKey: suiteKey,
BKey: bkey,
Block: block,
}
return c
}
func (c *DingTalkCrypto) GetDecryptMsg(signature, timestamp, nonce, secretMsg string) (string, error) {
if !c.VerificationSignature(c.Token, timestamp, nonce, secretMsg, signature) {
return "", errors.New("ERROR: 签名不匹配")
}
decode, err := base64.StdEncoding.DecodeString(secretMsg)
if err != nil {
return "", err
}
if len(decode) < aes.BlockSize {
return "", errors.New("ERROR: 密文太短")
}
blockMode := cipher.NewCBCDecrypter(c.Block, c.BKey[:c.Block.BlockSize()])
plantText := make([]byte, len(decode))
blockMode.CryptBlocks(plantText, decode)
plantText = pkCS7UnPadding(plantText)
size := binary.BigEndian.Uint32(plantText[16:20])
plantText = plantText[20:]
corpID := plantText[size:]
if string(corpID) != c.SuiteKey {
return "", errors.New("ERROR: CorpID匹配不正确")
}
return string(plantText[:size]), nil
}
func (c *DingTalkCrypto) GetEncryptMsg(msg, timestamp, nonce string) (string, string, error) {
size := make([]byte, 4)
binary.BigEndian.PutUint32(size, uint32(len(msg)))
msg = randomString(16) + string(size) + msg + c.SuiteKey
plantText := pkCS7Padding([]byte(msg), c.Block.BlockSize())
if len(plantText)%aes.BlockSize != 0 {
return "", "", errors.New("ERROR: 消息体size不为16的倍数")
}
blockMode := cipher.NewCBCEncrypter(c.Block, c.BKey[:c.Block.BlockSize()])
chipherText := make([]byte, len(plantText))
blockMode.CryptBlocks(chipherText, plantText)
outMsg := base64.StdEncoding.EncodeToString(chipherText)
signature := c.CreateSignature(c.Token, timestamp, nonce, string(outMsg))
return string(outMsg), signature, nil
}
// 数据签名
func (c *DingTalkCrypto) CreateSignature(token, timestamp, nonce, msg string) string {
params := make([]string, 0)
params = append(params, token)
params = append(params, timestamp)
params = append(params, nonce)
params = append(params, msg)
sort.Strings(params)
return sha1Sign(strings.Join(params, ""))
}
// 验证数据签名
func (c *DingTalkCrypto) VerificationSignature(token, timestamp, nonce, msg, sigture string) bool {
return c.CreateSignature(token, timestamp, nonce, msg) == sigture
}
// 解密补位
func pkCS7UnPadding(plantText []byte) []byte {
length := len(plantText)
unpadding := int(plantText[length-1])
return plantText[:(length - unpadding)]
}
// 加密补位
func pkCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
// 随机字符串
func randomString(n int, alphabets ...byte) string {
const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var bytes = make([]byte, n)
var randby bool
if num, err := rand.Read(bytes); num != n || err != nil {
r.Seed(time.Now().UnixNano())
randby = true
}
for i, b := range bytes {
if len(alphabets) == 0 {
if randby {
bytes[i] = alphanum[r.Intn(len(alphanum))]
} else {
bytes[i] = alphanum[b%byte(len(alphanum))]
}
} else {
if randby {
bytes[i] = alphabets[r.Intn(len(alphabets))]
} else {
bytes[i] = alphabets[b%byte(len(alphabets))]
}
}
}
return string(bytes)
}