|
| 1 | +package kernel |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "crypto/aes" |
| 6 | + "crypto/sha1" |
| 7 | + "encoding/base64" |
| 8 | + "encoding/binary" |
| 9 | + "encoding/xml" |
| 10 | + "fmt" |
| 11 | + "github.com/ArtisanCloud/go-wechat/src/kernel/Support" |
| 12 | + "math/rand" |
| 13 | + "sort" |
| 14 | + "strings" |
| 15 | +) |
| 16 | + |
| 17 | +// Wechat Docs: https://open.work.weixin.qq.com/api/doc/90000/90138/90307 |
| 18 | +const ( |
| 19 | + ErrorInvalidSignature = -40001 // 签名验证错误 |
| 20 | + ErrorParseXml = -40002 // xml/json解析失败 |
| 21 | + ErrorCalcSignature = -40003 // sha加密生成签名失败 |
| 22 | + ErrorInvalidAesKey = -40004 // AESKey 非法 |
| 23 | + ErrorInvalidAppId = -40005 // ReceiveId 校验错误 |
| 24 | + ErrorEncryptAes = -40006 // AES 加密失败 |
| 25 | + ErrorDecryptAes = -40007 // AES 解密失败 |
| 26 | + ErrorInvalidXml = -40008 // 解密后得到的buffer非法 |
| 27 | + ErrorBase64Encode = -40009 // base64 编码失败 |
| 28 | + ErrorBase64Decode = -40010 // base64 解码失败 |
| 29 | + ErrorXmlBuild = -40011 // 生成xml失败 |
| 30 | + IllegalBuffer = -41003 // Illegal buffer |
| 31 | + letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 32 | +) |
| 33 | + |
| 34 | +type CDATA struct { |
| 35 | + Value string `xml:",cdata"` |
| 36 | +} |
| 37 | + |
| 38 | +type WeComReplyMsg struct { |
| 39 | + XMLName xml.Name `xml:"xml"` |
| 40 | + Encrypt CDATA `xml:"Encrypt"` |
| 41 | + Signature CDATA `xml:"MsgSignature"` |
| 42 | + Timestamp string `xml:"TimeStamp"` |
| 43 | + Nonce CDATA `xml:"Nonce"` |
| 44 | +} |
| 45 | + |
| 46 | +type WeComRecvMsg struct { |
| 47 | + ToUserName string `xml:"ToUserName"` |
| 48 | + Encrypt string `xml:"Encrypt"` |
| 49 | + AgentId string `xml:"AgentID"` |
| 50 | +} |
| 51 | + |
| 52 | +type Encryptor struct { |
| 53 | + appId string // App token |
| 54 | + token string |
| 55 | + aesKey []byte |
| 56 | + blockSize int |
| 57 | + aes *Support.AES |
| 58 | +} |
| 59 | + |
| 60 | +func NewEncryptor(appId, token, aesKey string) (*Encryptor, error) { |
| 61 | + // TODO: 不明白为什么需要等号 |
| 62 | + aesKey = aesKey + "=" |
| 63 | + aesKeyByte, err := base64.StdEncoding.DecodeString(aesKey) |
| 64 | + if err != nil { |
| 65 | + return nil, err |
| 66 | + } |
| 67 | + return &Encryptor{ |
| 68 | + appId: appId, |
| 69 | + token: token, |
| 70 | + aesKey: aesKeyByte, |
| 71 | + blockSize: 32, |
| 72 | + aes: &Support.AES{}, |
| 73 | + }, nil |
| 74 | +} |
| 75 | + |
| 76 | +// GetToken Get the app token |
| 77 | +func (encryptor *Encryptor) GetToken() string { |
| 78 | + return encryptor.token |
| 79 | +} |
| 80 | + |
| 81 | +func (encryptor *Encryptor) randString(n int) string { |
| 82 | + b := make([]byte, n) |
| 83 | + for i := range b { |
| 84 | + b[i] = letterBytes[rand.Int63()%int64(len(letterBytes))] |
| 85 | + } |
| 86 | + return string(b) |
| 87 | +} |
| 88 | + |
| 89 | +// Encrypt encrypt xml msg and return xml |
| 90 | +func (encryptor *Encryptor) Encrypt(msg, nonce, timestamp string) ([]byte, *Support.CryptError) { |
| 91 | + |
| 92 | + randStr := encryptor.randString(16) |
| 93 | + var buffer bytes.Buffer |
| 94 | + buffer.WriteString(randStr) |
| 95 | + |
| 96 | + msgLenBuf := make([]byte, 4) |
| 97 | + binary.BigEndian.PutUint32(msgLenBuf, uint32(len(msg))) |
| 98 | + buffer.Write(msgLenBuf) |
| 99 | + buffer.WriteString(msg) |
| 100 | + |
| 101 | + // TODO 暂时不知道用途 |
| 102 | + //buffer.WriteString(wxBizMsgCrypt.receiverId) |
| 103 | + |
| 104 | + tmpCiphertext, err := encryptor.aes.Encrypt(buffer.Bytes(), encryptor.aesKey, encryptor.aesKey[:aes.BlockSize]) |
| 105 | + if err != nil { |
| 106 | + return nil, (*Support.CryptError)(err) |
| 107 | + } |
| 108 | + ciphertext := string(tmpCiphertext) |
| 109 | + |
| 110 | + signature := encryptor.Signature(encryptor.token, timestamp, nonce, ciphertext) |
| 111 | + |
| 112 | + msg4Send := &WeComReplyMsg{ |
| 113 | + Encrypt: CDATA{Value: ciphertext}, |
| 114 | + Signature: CDATA{Value: signature}, |
| 115 | + Timestamp: timestamp, |
| 116 | + Nonce: CDATA{Value: nonce}, |
| 117 | + } |
| 118 | + //msg4Send := NewWXBizMsg4Send(ciphertext, signature, timestamp, nonce) |
| 119 | + //msg.Marshal() |
| 120 | + xmlByte, err2 := xml.Marshal(msg4Send) |
| 121 | + if err2 != nil { |
| 122 | + return nil, Support.NewCryptError(ErrorXmlBuild, err2.Error()) |
| 123 | + } |
| 124 | + return xmlByte, nil |
| 125 | +} |
| 126 | + |
| 127 | +// Decrypt decrypt xml msg and return xml |
| 128 | +func (encryptor *Encryptor) Decrypt(content []byte, msgSignature, nonce, timestamp string) ([]byte, *Support.CryptError) { |
| 129 | + var msg4Recv WeComRecvMsg |
| 130 | + err := xml.Unmarshal(content, &msg4Recv) |
| 131 | + |
| 132 | + if err != nil { |
| 133 | + return nil, Support.NewCryptError(ErrorDecryptAes, err.Error()) |
| 134 | + } |
| 135 | + |
| 136 | + signature := encryptor.Signature(encryptor.token, timestamp, nonce, msg4Recv.Encrypt) |
| 137 | + |
| 138 | + if strings.Compare(signature, msgSignature) != 0 { |
| 139 | + return nil, Support.NewCryptError(ErrorCalcSignature, "signature not equal") |
| 140 | + } |
| 141 | + |
| 142 | + iv := encryptor.aesKey[:aes.BlockSize] |
| 143 | + plaintext, cryptErr := encryptor.aes.Decrypt(msg4Recv.Encrypt, encryptor.aesKey, iv) |
| 144 | + //plaintext, cryptErr := wxBizMsgCrypt.cbcDecrypter(msg4Recv.Encrypt) |
| 145 | + if nil != cryptErr { |
| 146 | + return nil, cryptErr |
| 147 | + } |
| 148 | + |
| 149 | + plaintext, cryptErr = encryptor.aes.PKCS7UnPadding(plaintext) |
| 150 | + if cryptErr != nil { |
| 151 | + return nil, cryptErr |
| 152 | + } |
| 153 | + |
| 154 | + textLen := uint32(len(plaintext)) |
| 155 | + if textLen < 20 { |
| 156 | + return nil, Support.NewCryptError(IllegalBuffer, "plain is to small 1") |
| 157 | + } |
| 158 | + //random := plaintext[:16] |
| 159 | + msgLen := binary.BigEndian.Uint32(plaintext[16:20]) |
| 160 | + if textLen < (20 + msgLen) { |
| 161 | + return nil, Support.NewCryptError(IllegalBuffer, "plain is to small 2") |
| 162 | + } |
| 163 | + |
| 164 | + msg := plaintext[20 : 20+msgLen] |
| 165 | + //receiverId := plaintext[20+msgLen:] |
| 166 | + |
| 167 | + return msg, nil |
| 168 | +} |
| 169 | + |
| 170 | +// VerifyUrl Parsing the official WeChat callback validation. |
| 171 | +// Wechat Docs: https://work.weixin.qq.com/api/doc/90000/90135/90235 |
| 172 | +// When adding URLs to the WeChat admin backend, WeChat will trigger a GET request to verify whether the server can process the encrypted information properly, and the message needs to be decrypted and returned. |
| 173 | +// 在微信管理后台添加URL的时候,微信会触发一条GET请求用于验证服务器能否正常处理加密信息,需要将消息解密出来返回。 |
| 174 | +// eg: "/app-callback?msg_signature=1495c4dfd4958d4e5faf618978ae66943a042f87×tamp=1623292419&nonce=1623324060&echostr=o1XtmVltGmUAqoWee54yd4Q5ZBgrw4%2F9lFo5qdZoVPd1DybzarjuYCfFlR2AFbAcWHwFgmbrVBD%2Bf9910QIF6g%3D%3D" |
| 175 | +func (encryptor *Encryptor) VerifyUrl(content string, msgSignature, nonce, timestamp string) ([]byte, *Support.CryptError) { |
| 176 | + msg4Recv := &WeComRecvMsg{ |
| 177 | + Encrypt: content, |
| 178 | + } |
| 179 | + msg4RecvByte, err := xml.Marshal(msg4Recv) |
| 180 | + if err != nil { |
| 181 | + return nil, Support.NewCryptError(ErrorXmlBuild, err.Error()) |
| 182 | + } |
| 183 | + return encryptor.Decrypt(msg4RecvByte, msgSignature, nonce, timestamp) |
| 184 | +} |
| 185 | + |
| 186 | +// Signature get sha1 |
| 187 | +func (encryptor *Encryptor) Signature(token, timestamp, nonce, data string) string { |
| 188 | + sortArr := []string{token, timestamp, nonce, data} |
| 189 | + sort.Strings(sortArr) |
| 190 | + var buffer bytes.Buffer |
| 191 | + for _, value := range sortArr { |
| 192 | + buffer.WriteString(value) |
| 193 | + } |
| 194 | + |
| 195 | + sha := sha1.New() |
| 196 | + sha.Write(buffer.Bytes()) |
| 197 | + signature := fmt.Sprintf("%x", sha.Sum(nil)) |
| 198 | + return signature |
| 199 | +} |
0 commit comments