heyuntao
2023-05-05 cc09b6fe6ffac34a4eeeb26d313b187713cae0de
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Linq;
 
namespace CommonUtil.Security
{
    /// <summary>
    /// 安全工具类
    /// </summary>
    public abstract class SecurityUtil
    {
        private static readonly char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".ToCharArray();
        private static readonly int[] IA = InitIA();
        private static readonly int KeySize = 128;
        private static readonly int BlockSize = 128;
        private static readonly byte[] IvBytes = Encoding.UTF8.GetBytes("0102030405060708");//初始向量
 
        /// <summary>
        /// 初始化
        /// </summary>
        /// <returns></returns>
        private static int[] InitIA()
        {
            int len = 256;
            int[] a = new int[len];
            for (int i = 0; i < len; i++)
            {
                a[i] = -1;
            }
 
            for (int i = 0, iS = CA.Length; i < iS; i++)
            {
                a[CA[i]] = i;
            }
            a['='] = 0;
            return a;
        }
 
        /// <summary>
        /// 判断是否base64值
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsBase64Value(string str)
        {
            // Check special case
            int sLen = str != null ? str.Length : 0;
            if (sLen == 0)
                return false;
 
            // Count illegal characters (including '\r', '\n') to know what size the returned array will be,
            // so we don't have to reallocate & copy it later.
            int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
            for (int i = 0; i < sLen; i++)  // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
            {
                char currentChar = str[i];
                if (currentChar >= IA.Length)
                {
                    return false;
                }
 
                if (IA[currentChar] < 0)
                {
                    sepCnt++;
                }
 
            }
 
 
            // Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
            if ((sLen - sepCnt) % 4 != 0)
            {
                return false;
            }
            return true;
        }
 
        /// <summary>
        /// 生成滑动窗口
        /// </summary>
        /// <param name="input">数据</param>
        /// <param name="slideSize">分词大小</param>
        /// <returns>分词元素</returns>
        public static List<string> GetSlideWindows(string input, int slideSize)
        {
            List<string> windows = new List<string>();
            int startIndex = 0;
            int endIndex = 0;
            int currentWindowSize = 0;
            string currentWindow = null;
 
            while (endIndex < input.Length || currentWindowSize > slideSize)
            {
                bool startsWithLetterOrDigit;
                if (currentWindow == null)
                {
                    startsWithLetterOrDigit = false;
                }
                else
                {
                    startsWithLetterOrDigit = IsLetterOrDigit(currentWindow[0]);
                }
 
                if (endIndex == input.Length && !startsWithLetterOrDigit)
                {
                    break;
                }
 
                if (currentWindowSize == slideSize && !startsWithLetterOrDigit && IsLetterOrDigit(input[endIndex]))
                {
                    endIndex++;
                    currentWindow = input.Substring(startIndex, endIndex - startIndex);
                    currentWindowSize = 5;
 
                }
                else
                {
                    if (endIndex != 0)
                    {
                        if (startsWithLetterOrDigit)
                        {
                            currentWindowSize -= 1;
                        }
                        else
                        {
                            currentWindowSize -= 2;
                        }
                        startIndex++;
                    }
 
                    while (currentWindowSize < slideSize && endIndex < input.Length)
                    {
                        char currentChar = input[endIndex];
                        if (IsLetterOrDigit(currentChar))
                        {
                            currentWindowSize += 1;
                        }
                        else
                        {
                            currentWindowSize += 2;
                        }
                        endIndex++;
                    }
                    currentWindow = input.Substring(startIndex, endIndex - startIndex);
 
                }
                windows.Add(currentWindow);
            }
            return windows;
        }
 
        /// <summary>
        /// 判断是否小写字母
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        private static bool IsLetterOrDigit(char x)
        {
            if (0 <= x && x <= 127)
            {
                return true;
            }
            return false;
        }
 
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="input"></param>
        /// <param name="toLength"></param>
        /// <returns></returns>
        private static byte[] Compress(byte[] input, int toLength)
        {
            if (toLength < 0)
            {
                return null;
            }
            byte[] output = new byte[toLength];
            for (int i = 0; i < output.Length; i++)
            {
                output[i] = 0;
            }
 
            for (int i = 0; i < input.Length; i++)
            {
                int index_output = i % toLength;
                output[index_output] ^= input[i];
            }
 
            return output;
        }
 
        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <param name="encode">编码方式</param>
        /// <returns></returns>
        public static string EncodeBase64(string source, Encoding encode)
        {
            byte[] bytes = encode.GetBytes(source);
            return Convert.ToBase64String(bytes);
        }
 
        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <returns></returns>
        /// 
        /// <seealso cref="EncodeBase64(string,Encoding)">  
        /// 参看SecurityUtil.EncodeBase64(string,Encoding)方法的说明 </seealso>  
        public static string EncodeBase64(string source)
        {
            return EncodeBase64(source, Encoding.UTF8);
        }
 
        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="str">需要加密的字符串</param>
        /// <param name="key">密钥</param>
        /// <param name="iv">偏移量</param>
        /// <returns>加密后的密文</returns>
        public static string DesEncrypt(string str, string key, string iv)
        {
            if (str.IsNullOrEmpty() || key.IsNullOrEmpty() || iv.IsNullOrEmpty())
            {
                return null;
            }
            var bKey = new byte[8];
            Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(8)), bKey, 8);
            var bIv = new byte[8];
            Array.Copy(Encoding.UTF8.GetBytes(iv.PadRight(8)), bIv, 8);
            var oldbytes = Encoding.UTF8.GetBytes(str);
 
            using (var dcsp = new DESCryptoServiceProvider())//using(){}:{}语句执行完后会将()中的释放,相当于dcsp.Dispose();
            {
                using (var ms = new MemoryStream())
                {
                    var cs = new CryptoStream(ms, dcsp.CreateEncryptor(bKey, bIv), CryptoStreamMode.Write);
                    cs.Write(oldbytes, 0, oldbytes.Length);
                    cs.FlushFinalBlock();
                    var newbytes = ms.ToArray();
                    cs.Dispose();//释放cs
                    return Convert.ToBase64String(newbytes);
                }
            }
        }
 
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="str">需要解密的密文</param>
        /// <param name="key">密钥</param>
        /// <param name="iv">偏移量</param>
        /// <returns>解密后的字符串</returns>
        public static string DesDecrypt(string str, string key, string iv)
        {
            if (str.IsNullOrEmpty() || key.IsNullOrEmpty() || key.IsNullOrEmpty())
            {
                return null;
            }
            var bKey = new byte[8];
            Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(8)), bKey, 8);
            var bIv = new byte[8];
            Array.Copy(Encoding.UTF8.GetBytes(iv.PadRight(8)), bIv, 8);
            var oldbytes = Convert.FromBase64String(str);
 
            using (var dcsp = new DESCryptoServiceProvider())
            {
                using (var ms = new MemoryStream())
                {
                    var cs = new CryptoStream(ms, dcsp.CreateDecryptor(bKey, bIv), CryptoStreamMode.Write);
                    cs.Write(oldbytes, 0, oldbytes.Length);
                    cs.FlushFinalBlock();
                    var newBytes = ms.ToArray();
                    cs.Dispose();
                    return Encoding.UTF8.GetString(newBytes);
                }
            }
        }
 
        /// <summary>
        /// AES加密 
        /// </summary>
        /// <param name="context">待加密的内容</param>
        /// <param name="keyBytes">加密密钥</param>
        /// <returns></returns>
        public static string AesEncrypt(string context, byte[] keyBytes)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
 
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;
            rijndaelCipher.KeySize = KeySize;
            rijndaelCipher.BlockSize = KeySize;
 
 
            // 加密密钥
            rijndaelCipher.Key = keyBytes;
            rijndaelCipher.IV = IvBytes;
 
            ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
 
            byte[] plainText = Encoding.UTF8.GetBytes(context);
            byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
            return Convert.ToBase64String(cipherBytes);
        }
 
        /// <summary>
        /// AES解密
        /// </summary>
        /// <param name="context"></param>
        /// <param name="keyBytes"></param>
        /// <returns></returns>
        public static string AesDecrypt(string context, byte[] keyBytes)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
 
            rijndaelCipher.Mode = CipherMode.CBC;
            rijndaelCipher.Padding = PaddingMode.PKCS7;
            rijndaelCipher.KeySize = KeySize;
            rijndaelCipher.BlockSize = BlockSize;
 
            byte[] encryptedData = Convert.FromBase64String(context);
            rijndaelCipher.Key = keyBytes;
            rijndaelCipher.IV = IvBytes;
 
            ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
 
            byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
            return Encoding.UTF8.GetString(plainText);
        }
 
        /// <summary>
        /// Aes加密
        /// </summary>
        /// <param name="str">需要加密的字符串</param>
        /// <param name="key">密钥,长度不够时空格补齐,超过时从左截取</param>
        /// <param name="iv">偏移量,长度不够时空格补齐,超过时从左截取</param>
        /// <param name="keyLenth">秘钥长度,16 24 32</param>
        /// <param name="aesMode">加密模式</param>
        /// <param name="aesPadding">填充方式</param>
        /// <returns></returns>
        public static string AesEncrypt(string str, string key, string iv, int keyLenth = 16, CipherMode aesMode = CipherMode.CBC, PaddingMode aesPadding = PaddingMode.PKCS7)
        {
            //对称加密和分组加密中的四种模式(ECB、CBC、CFB、OFB) 。
            if (str.IsNullOrEmpty() || key.IsNullOrEmpty() || iv.IsNullOrEmpty())
            {
                return null;
            }
            if (!new List<int> { 16, 24, 32 }.Contains(keyLenth))
            {
                return null;//密钥的长度,16位密钥 = 128位,24位密钥 = 192位,32位密钥 = 256位。
            }
            var oldBytes = Encoding.UTF8.GetBytes(str);
 
            key = key.Length > keyLenth ? key.Substring(0, keyLenth) : key.Length < keyLenth ? key.PadRight(keyLenth) : key;
            iv = iv.Length > 16 ? iv.Substring(0, 16) : iv.Length < 16 ? iv.PadRight(16) : iv;
            var bKey = Encoding.UTF8.GetBytes(key);
            var bIv = Encoding.UTF8.GetBytes(iv);
 
            var rijalg = new RijndaelManaged
            {
                Mode = aesMode,
                Padding = aesPadding,
                Key = bKey,
                IV = bIv,
            };
            var decryptor = rijalg.CreateEncryptor(rijalg.Key, rijalg.IV);
            var rtByte = decryptor.TransformFinalBlock(oldBytes, 0, oldBytes.Length);
            return Convert.ToBase64String(rtByte);
        }
 
        /// <summary>
        /// Aes解密
        /// </summary>
        /// <param name="str">需要解密的字符串</param>
        /// <param name="key">密钥,长度不够时空格补齐,超过时从左截取</param>
        /// <param name="iv">偏移量,长度不够时空格补齐,超过时从左截取</param>
        /// <param name="keyLenth">秘钥长度,16 24 32</param>
        /// <param name="aesMode">解密模式</param>
        /// <param name="aesPadding">填充方式</param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key, string iv, int keyLenth = 16, CipherMode aesMode = CipherMode.CBC, PaddingMode aesPadding = PaddingMode.PKCS7)
        {
            if (str.IsNullOrEmpty() || key.IsNullOrEmpty() || iv.IsNullOrEmpty())
            {
                return null;
            }
            if (!new List<int> { 16, 24, 32 }.Contains(keyLenth))
            {
                return null;//密钥的长度,16位密钥 = 128位,24位密钥 = 192位,32位密钥 = 256位。
            }
            var oldBytes = Convert.FromBase64String(str);
 
            key = key.Length > keyLenth ? key.Substring(0, keyLenth) : key.Length < keyLenth ? key.PadRight(keyLenth) : key;
            iv = iv.Length > 16 ? iv.Substring(0, 16) : iv.Length < 16 ? iv.PadRight(16) : iv;
            var bKey = Encoding.UTF8.GetBytes(key);
            var bIv = Encoding.UTF8.GetBytes(iv);
 
            var rijalg = new RijndaelManaged
            {
                Mode = aesMode,
                Padding = aesPadding,
                Key = bKey,
                IV = bIv,
            };
            var decryptor = rijalg.CreateDecryptor(rijalg.Key, rijalg.IV);
            var rtByte = decryptor.TransformFinalBlock(oldBytes, 0, oldBytes.Length);
            return Encoding.UTF8.GetString(rtByte);
        }
 
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">明文</param>
        /// <param name="isBase64">密文采用Base64还是等效16进制字符串</param>
        /// <returns>密文</returns>
        public static string MD5Encrypt(string str, bool isBase64 = false)
        {
            if (str.IsNullOrEmpty())
            {
                return null;
            }
            var oldBytes = Encoding.UTF8.GetBytes(str);
            MD5 md5 = new MD5CryptoServiceProvider();
            var newBytes = md5.ComputeHash(oldBytes);
            var result = isBase64 ? Convert.ToBase64String(newBytes) : BitConverter.ToString(newBytes).Replace("-", "");
            return result;
        }
 
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">明文</param>
        /// <returns>密文</returns>
        public static byte[] MD5Encrypt(string str)
        {
            MD5 md5 = MD5.Create();
            byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
 
            return bytes;
        }
 
        /// <summary>
        /// HmacMD5加密
        /// </summary>
        /// <param name="encryptText"></param>
        /// <param name="encryptKey"></param>
        /// <returns></returns>
        public static byte[] HmacMD5Encrypt(string encryptText, byte[] encryptKey)
        {
            HMACMD5 hmac = new HMACMD5(encryptKey);
            byte[] bytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(encryptText));
            return bytes;
        }
 
        /// <summary>
        /// 生成BASE64(H_MAC)
        /// </summary>
        /// <param name="encryptText">被签名的字符串</param>
        /// <param name="encryptKey">秘钥</param>
        /// <returns></returns>
        public static string HmacMD5EncryptToBase64(string encryptText, byte[] encryptKey)
        {
            return Convert.ToBase64String(HmacMD5Encrypt(encryptText, encryptKey));
        }
 
        /// <summary>
        /// 生成BASE64(H_MAC),压缩H_MAC值
        /// </summary>
        /// <param name="encryptText"></param>
        /// <param name="encryptKey"></param>
        /// <param name="compressLen"></param>
        /// <returns></returns>
        public static string HmacMD5EncryptToBase64(string encryptText, byte[] encryptKey, int compressLen)
        {
            return Convert.ToBase64String(Compress(HmacMD5Encrypt(encryptText, encryptKey), compressLen));
        }
 
        /// <summary>
        /// 签名.MD5加密,32位大写
        /// </summary>
        /// <param name="parameters"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static string SignRequest(IDictionary<string, string> parameters, string secret)
        {
            // 第一步:把字典按Key的字母顺序排序
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters, StringComparer.Ordinal);
 
            // 第二步:把所有参数名和参数值串在一起
            StringBuilder query = new StringBuilder();
 
            query.Append(secret);
 
            foreach (KeyValuePair<string, string> kv in sortedParams)
            {
                if (!string.IsNullOrEmpty(kv.Key) && !string.IsNullOrEmpty(kv.Value))
                {
                    query.Append(kv.Key).Append(kv.Value);
                }
            }
 
            query.Append(secret);
 
            // 第三步:MD5加密
            byte[] bytes = MD5Encrypt(query.ToString());
 
            // 第四步:把二进制转化为大写的十六进制
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                result.Append(bytes[i].ToString("X2"));
            }
            return result.ToString();
        }
 
        /// <summary>
        /// 根据ID生成6位数邀请码
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static string createInvitecode(long Id)
        {
            string source_string = "2YU9IP6ASDFG8QWERTHJ7KLZX4CV5B3ONM1";//自定义35进制
            string code = "";
            long mod = 0;
            StringBuilder sb = new StringBuilder();
            while (Id > 0)
            {
                mod = Id % source_string.Length;
                Id = (Id - mod) / source_string.Length;
                code = source_string.ToCharArray()[mod] + code;
 
            }
            return code.PadRight(6, '0');//不足六位补0
        }
 
        /// <summary>
        /// 根据邀请码获取ID
        /// </summary>
        /// <param name="Invitecode"></param>
        /// <returns></returns>
        public static long deInvitecode(string Invitecode)
        {
            string source_string = "2YU9IP6ASDFG8QWERTHJ7KLZX4CV5B3ONM1";//自定义35进制
            Invitecode = new string((from s in Invitecode where s != '0' select s).ToArray());
            int num = 0;
            for (int i = 0; i < Invitecode.ToCharArray().Length; i++)
            {
                for (int j = 0; j < source_string.ToCharArray().Length; j++)
                {
                    if (Invitecode.ToCharArray()[i] == source_string.ToCharArray()[j])
                    {
                        num += j * Convert.ToInt32(Math.Pow(source_string.Length, Invitecode.ToCharArray().Length - i - 1));
                    }
                }
            }
            return num;
        }
 
    }
}