zhaojs
2023-09-15 fc13938ff90213060532d99a600dea4a84456885
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
 
namespace Api.MessageReceive.Service
{
    internal class QwCryptography
    {
 
        public static UInt32 HostToNetworkOrder(UInt32 inval)
        {
            UInt32 outval = 0;
            for (int i = 0; i < 4; i++)
                outval = (outval << 8) + ((inval >> (i * 8)) & 255);
            return outval;
        }
 
        public static Int32 HostToNetworkOrder(Int32 inval)
        {
            Int32 outval = 0;
            for (int i = 0; i < 4; i++)
                outval = (outval << 8) + ((inval >> (i * 8)) & 255);
            return outval;
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="encodingAESKey"></param>
        /// <param name="corpid"></param>
        /// <returns></returns>
        public static string AES_decrypt(String input, string encodingAESKey, ref string corpid)
        {
            byte[] key;
            key = Convert.FromBase64String(encodingAESKey + "=");
            byte[] iv = new byte[16];
            Array.Copy(key, iv, 16);
            byte[] btmpMsg = AES_decrypt(input, iv, key);
 
            int len = BitConverter.ToInt32(btmpMsg, 16);
            len = IPAddress.NetworkToHostOrder(len);
 
            byte[] bMsg = new byte[len];
            byte[] bCorpid = new byte[btmpMsg.Length - 20 - len];
            Array.Copy(btmpMsg, 20, bMsg, 0, len);
            Array.Copy(btmpMsg, 20 + len, bCorpid, 0, btmpMsg.Length - 20 - len);
            string oriMsg = Encoding.UTF8.GetString(bMsg);
            corpid = Encoding.UTF8.GetString(bCorpid);
 
            return oriMsg;
        }
 
        public static String AES_encrypt(String input, string encodingAESKey, string corpid)
        {
            byte[] key;
            key = Convert.FromBase64String(encodingAESKey + "=");
            byte[] iv = new byte[16];
            Array.Copy(key, iv, 16);
            string randcode = CreateRandCode(16);
            byte[] bRand = Encoding.UTF8.GetBytes(randcode);
            byte[] bCorpid = Encoding.UTF8.GetBytes(corpid);
            byte[] btmpMsg = Encoding.UTF8.GetBytes(input);
            byte[] bMsgLen = BitConverter.GetBytes(HostToNetworkOrder(btmpMsg.Length));
            byte[] bMsg = new byte[bRand.Length + bMsgLen.Length + bCorpid.Length + btmpMsg.Length];
 
            Array.Copy(bRand, bMsg, bRand.Length);
            Array.Copy(bMsgLen, 0, bMsg, bRand.Length, bMsgLen.Length);
            Array.Copy(btmpMsg, 0, bMsg, bRand.Length + bMsgLen.Length, btmpMsg.Length);
            Array.Copy(bCorpid, 0, bMsg, bRand.Length + bMsgLen.Length + btmpMsg.Length, bCorpid.Length);
 
            return AES_encrypt(bMsg, iv, key);
        }
 
        private static string CreateRandCode(int codeLen)
        {
            string codeSerial = "2,3,4,5,6,7,a,c,d,e,f,h,i,j,k,m,n,p,r,s,t,A,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z";
            if (codeLen == 0)
            {
                codeLen = 16;
            }
            string[] arr = codeSerial.Split(',');
            string code = "";
            int randValue = -1;
            Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
            for (int i = 0; i < codeLen; i++)
            {
                randValue = rand.Next(0, arr.Length - 1);
                code += arr[randValue];
            }
            return code;
        }
 
        private static String AES_encrypt(String input, byte[] iv, byte[] key)
        {
            var aes = new RijndaelManaged();
            //秘钥的大小,以位为单位
            aes.KeySize = 256;
            //支持的块大小
            aes.BlockSize = 128;
            //填充模式
            aes.Padding = PaddingMode.PKCS7;
            aes.Mode = CipherMode.CBC;
            aes.Key = key;
            aes.IV = iv;
            var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
            byte[] xBuff = null;
 
            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                {
                    byte[] xXml = Encoding.UTF8.GetBytes(input);
                    cs.Write(xXml, 0, xXml.Length);
                }
                xBuff = ms.ToArray();
            }
            String output = Convert.ToBase64String(xBuff);
            return output;
        }
 
        private static String AES_encrypt(byte[] input, byte[] iv, byte[] key)
        {
            var aes = new RijndaelManaged();
            //秘钥的大小,以位为单位
            aes.KeySize = 256;
            //支持的块大小
            aes.BlockSize = 128;
            //填充模式
            //aes.Padding = PaddingMode.PKCS7;
            aes.Padding = PaddingMode.None;
            aes.Mode = CipherMode.CBC;
            aes.Key = key;
            aes.IV = iv;
            var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
            byte[] xBuff = null;
 
            #region 自己进行PKCS7补位,用系统自己带的不行
 
            byte[] msg = new byte[input.Length + 32 - input.Length % 32];
            Array.Copy(input, msg, input.Length);
            byte[] pad = KCS7Encoder(input.Length);
            Array.Copy(pad, 0, msg, input.Length, pad.Length);
 
            #endregion 自己进行PKCS7补位,用系统自己带的不行
 
            #region 注释的也是一种方法,效果一样
 
            //ICryptoTransform transform = aes.CreateEncryptor();
            //byte[] xBuff = transform.TransformFinalBlock(msg, 0, msg.Length);
 
            #endregion 注释的也是一种方法,效果一样
 
            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                {
                    cs.Write(msg, 0, msg.Length);
                }
                xBuff = ms.ToArray();
            }
 
            String output = Convert.ToBase64String(xBuff);
            return output;
        }
 
        private static byte[] KCS7Encoder(int text_length)
        {
            int block_size = 32;
            // 计算需要填充的位数
            int amount_to_pad = block_size - (text_length % block_size);
            if (amount_to_pad == 0)
            {
                amount_to_pad = block_size;
            }
            // 获得补位所用的字符
            char pad_chr = Chr(amount_to_pad);
            string tmp = "";
            for (int index = 0; index < amount_to_pad; index++)
            {
                tmp += pad_chr;
            }
            return Encoding.UTF8.GetBytes(tmp);
        }
 
        /**
         * 将数字转化成ASCII码对应的字符,用于对明文进行补码
         *
         * @param a 需要转化的数字
         * @return 转化得到的字符
         */
 
        private static char Chr(int a)
        {
            byte target = (byte)(a & 0xFF);
            return (char)target;
        }
 
        private static byte[] AES_decrypt(String input, byte[] iv, byte[] key)
        {
            RijndaelManaged aes = new RijndaelManaged();
            aes.KeySize = 256;
            aes.BlockSize = 128;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.None;
            aes.Key = key;
            aes.IV = iv;
            var decrypt = aes.CreateDecryptor(aes.Key, aes.IV);
            byte[] xBuff = null;
            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
                {
                    byte[] xXml = Convert.FromBase64String(input);
                    byte[] msg = new byte[xXml.Length + 32 - xXml.Length % 32];
                    Array.Copy(xXml, msg, xXml.Length);
                    cs.Write(xXml, 0, xXml.Length);
                }
                xBuff = Decode2(ms.ToArray());
            }
            return xBuff;
        }
 
        private static byte[] Decode2(byte[] decrypted)
        {
            int pad = (int)decrypted[decrypted.Length - 1];
            if (pad < 1 || pad > 32)
            {
                pad = 0;
            }
            byte[] res = new byte[decrypted.Length - pad];
            Array.Copy(decrypted, 0, res, 0, decrypted.Length - pad);
            return res;
        }
    }
 
    /// <summary>
    ///
    /// </summary>
    public class QwBizMsgCrypt
    {
        private string _sToken;
        private string _sEncodingAESKey;
        private string _m_sAppID;
 
        private enum QwBizMsgCryptErrorCode
        {
            WXBizMsgCrypt_OK = 0,
            WXBizMsgCrypt_ValidateSignature_Error = -40001,
            WXBizMsgCrypt_ParseXml_Error = -40002,
            WXBizMsgCrypt_ComputeSignature_Error = -40003,
            WXBizMsgCrypt_IllegalAesKey = -40004,
            WXBizMsgCrypt_ValidateCorpid_Error = -40005,
            WXBizMsgCrypt_EncryptAES_Error = -40006,
            WXBizMsgCrypt_DecryptAES_Error = -40007,
            WXBizMsgCrypt_IllegalBuffer = -40008,
            WXBizMsgCrypt_EncodeBase64_Error = -40009,
            WXBizMsgCrypt_DecodeBase64_Error = -40010
        };
 
        /// <summary>
        /// //构造函数
        /// @param sToken: 企业微信后台,开发者设置的Token
        /// @param sEncodingAESKey: 企业微信后台,开发者设置的EncodingAESKey
        /// @param sReceiveId: 不同场景含义不同,详见文档说明
        /// </summary>
        /// <param name="sToken"></param>
        /// <param name="sEncodingAESKey"></param>
        /// <param name="sReceiveId"></param>
        public QwBizMsgCrypt(string sToken, string sEncodingAESKey, string m_sAppID)
        {
            _sToken = sToken;
            _m_sAppID = m_sAppID;
            _sEncodingAESKey = sEncodingAESKey;
        }
 
        /// <summary>
        /// //验证URL
        /// @param sMsgSignature: 签名串,对应URL参数的msg_signature
        /// @param sTimeStamp: 时间戳,对应URL参数的timestamp
        /// @param sNonce: 随机串,对应URL参数的nonce
        /// @param sEchoStr: 随机串,对应URL参数的echostr
        /// @param sReplyEchoStr: 解密之后的echostr,当return返回0时有效
        /// @return:成功0,失败返回对应的错误码
        /// </summary>
        /// <param name="sMsgSignature"></param>
        /// <param name="sTimeStamp"></param>
        /// <param name="sNonce"></param>
        /// <param name="sEchoStr"></param>
        /// <param name="sReplyEchoStr"></param>
        /// <returns></returns>
        public int VerifyURL(string sMsgSignature, string sTimeStamp, string sNonce, string sEchoStr, ref string sReplyEchoStr)
        {
            try
            {
 
                int ret = 0;
                if (_sEncodingAESKey.Length != 43)
                {
                    return (int)QwBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
                }
                ret = VerifySignature(_sToken, sTimeStamp, sNonce, sEchoStr, sMsgSignature);
                if (0 != ret)
                {
                    return ret;
                }
                sReplyEchoStr = "";
                string cpid = "";
                try
                {
                    sReplyEchoStr = Cryptography.AES_decrypt(sEchoStr, _sEncodingAESKey, ref cpid); //m_sReceiveId);
                }
                catch (Exception)
                {
                    sReplyEchoStr = "";
                    return (int)QwBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error;
                }
            }
            catch (Exception)
            {
 
                return -1;
            }
 
            return 0;
        }
 
        /// <summary>
        /// // 检验消息的真实性,并且获取解密后的明文
        /// @param sMsgSignature: 签名串,对应URL参数的msg_signature
        /// @param sTimeStamp: 时间戳,对应URL参数的timestamp
        /// @param sNonce: 随机串,对应URL参数的nonce
        /// @param sPostData: 密文,对应POST请求的数据
        /// @param sMsg: 解密后的原文,当return返回0时有效
        /// @return: 成功0,失败返回对应的错误码
        /// </summary>
        /// <param name="sMsgSignature"></param>
        /// <param name="sTimeStamp"></param>
        /// <param name="sNonce"></param>
        /// <param name="sPostData"></param>
        /// <param name="sMsg"></param>
        /// <returns></returns>
        public int DecryptMsg(string sMsgSignature, string sTimeStamp, string sNonce, string sPostData, ref string sMsg)
        {
            if (_sEncodingAESKey.Length != 43)
            {
                return (int)QwBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
            }
            XmlDocument doc = new XmlDocument();
            XmlNode root;
            string sEncryptMsg;
            try
            {
                doc.LoadXml(sPostData);
                root = doc.FirstChild;
                sEncryptMsg = root["Encrypt"].InnerText;
            }
            catch (Exception)
            {
                return (int)QwBizMsgCryptErrorCode.WXBizMsgCrypt_ParseXml_Error;
            }
            //verify signature
            int ret = 0;
            ret = VerifySignature(_sToken, sTimeStamp, sNonce, sEncryptMsg, sMsgSignature);
            if (ret != 0)
                return ret;
            //decrypt
            string cpid = "";
            try
            {
                sMsg = Cryptography.AES_decrypt(sEncryptMsg, _sEncodingAESKey, ref cpid);
            }
            catch (FormatException)
            {
                sMsg = "";
                return (int)QwBizMsgCryptErrorCode.WXBizMsgCrypt_DecodeBase64_Error;
            }
            catch (Exception)
            {
                sMsg = "";
                return (int)QwBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error;
            }
            //if (cpid != _sReceiveId)
            //    return (int)QwBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateCorpid_Error;
            return 0;
        }
 
        /// <summary>
        /// //将企业号回复用户的消息加密打包
        /// @param sReplyMsg: 企业号待回复用户的消息,xml格式的字符串
        /// @param sTimeStamp: 时间戳,可以自己生成,也可以用URL参数的timestamp
        /// @param sNonce: 随机串,可以自己生成,也可以用URL参数的nonce
        /// @param sEncryptMsg: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,
        ///                        当return返回0时有效
        /// return:成功0,失败返回对应的错误码
        /// </summary>
        /// <param name="sReplyMsg"></param>
        /// <param name="sTimeStamp"></param>
        /// <param name="sNonce"></param>
        /// <param name="sEncryptMsg"></param>
        /// <returns></returns>
        public int EncryptMsg(string sReplyMsg, string sTimeStamp, string sNonce, ref string sEncryptMsg)
        {
            if (_sEncodingAESKey.Length != 43)
            {
                return (int)QwBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
            }
            string raw = "";
            try
            {
                raw = Cryptography.AES_encrypt(sReplyMsg, _sEncodingAESKey, _m_sAppID);
            }
            catch (Exception)
            {
                return (int)QwBizMsgCryptErrorCode.WXBizMsgCrypt_EncryptAES_Error;
            }
            string msgSigature = "";
            int ret = 0;
            ret = GenarateSinature(_sToken, sTimeStamp, sNonce, raw, ref msgSigature);
            if (0 != ret)
                return ret;
            sEncryptMsg = "";
 
            string encryptLabelHead = "<Encrypt><![CDATA[";
            string encryptLabelTail = "]]></Encrypt>";
            string msgSigLabelHead = "<MsgSignature><![CDATA[";
            string msgSigLabelTail = "]]></MsgSignature>";
            string timeStampLabelHead = "<TimeStamp><![CDATA[";
            string timeStampLabelTail = "]]></TimeStamp>";
            string nonceLabelHead = "<Nonce><![CDATA[";
            string nonceLabelTail = "]]></Nonce>";
            sEncryptMsg = sEncryptMsg + "<xml>" + encryptLabelHead + raw + encryptLabelTail;
            sEncryptMsg = sEncryptMsg + msgSigLabelHead + msgSigature + msgSigLabelTail;
            sEncryptMsg = sEncryptMsg + timeStampLabelHead + sTimeStamp + timeStampLabelTail;
            sEncryptMsg = sEncryptMsg + nonceLabelHead + sNonce + nonceLabelTail;
            sEncryptMsg += "</xml>";
            return 0;
        }
 
        /// <summary>
        ///
        /// </summary>
        public class DictionarySort : System.Collections.IComparer
        {
 
            /// <summary>
            ///
            /// </summary>
            /// <param name="oLeft"></param>
            /// <param name="oRight"></param>
            /// <returns></returns>
            public int Compare(object oLeft, object oRight)
            {
                string sLeft = oLeft as string;
                string sRight = oRight as string;
                int iLeftLength = sLeft.Length;
                int iRightLength = sRight.Length;
                int index = 0;
                while (index < iLeftLength && index < iRightLength)
                {
                    if (sLeft[index] < sRight[index])
                        return -1;
                    else if (sLeft[index] > sRight[index])
                        return 1;
                    else
                        index++;
                }
                return iLeftLength - iRightLength;
            }
        }
 
        //Verify Signature
        private static int VerifySignature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, string sSigture)
        {
            string hash = "";
            int ret = 0;
            ret = GenarateSinature(sToken, sTimeStamp, sNonce, sMsgEncrypt, ref hash);
            if (ret != 0)
                return ret;
            if (hash == sSigture)
                return 0;
            else
            {
                return (int)QwBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateSignature_Error;
            }
        }
 
        /// <summary>
        ///
        /// </summary>
        /// <param name="sToken"></param>
        /// <param name="sTimeStamp"></param>
        /// <param name="sNonce"></param>
        /// <param name="sMsgEncrypt"></param>
        /// <param name="sMsgSignature"></param>
        /// <returns></returns>
        public static int GenarateSinature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, ref string sMsgSignature)
        {
            ArrayList aL = new ArrayList();
            aL.Add(sToken);
            aL.Add(sTimeStamp);
            aL.Add(sNonce);
            aL.Add(sMsgEncrypt);
            aL.Sort(new DictionarySort());
            string raw = "";
            for (int i = 0; i < aL.Count; ++i)
            {
                raw += aL[i];
            }
 
            SHA1 sha;
            ASCIIEncoding enc;
            string hash = "";
            try
            {
                sha = new SHA1CryptoServiceProvider();
                enc = new ASCIIEncoding();
                byte[] dataToHash = enc.GetBytes(raw);
                byte[] dataHashed = sha.ComputeHash(dataToHash);
                hash = BitConverter.ToString(dataHashed).Replace("-", "");
                hash = hash.ToLower();
            }
            catch (Exception)
            {
                return (int)QwBizMsgCryptErrorCode.WXBizMsgCrypt_ComputeSignature_Error;
            }
            sMsgSignature = hash;
            return 0;
        }
    }
}