C#中各种数据加密方法

 
  
1 using System;
2   using System.Security ;
3 using System.Security.Cryptography ;
4 using System.Diagnostics ;
5
6 using System.Web;
7 using System.Text;
8 using System.IO;
9 using System.Web.Security;
10
11 namespace Utilities
12 {
13 /// <summary>
14 /// Summary description for Security.
15 /// </summary>
16 public class Security
17 {
18 public Security()
19 {
20 //
21 // TODO: Add constructor logic here
22 //
23 }
24
25
26 private char [] arr36Base = { ' 0 ' , ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' , ' 9 ' , ' A ' , ' B ' , ' C ' , ' D ' , ' E ' , ' F ' , ' G ' , ' H ' , ' I ' , ' J ' , ' K ' , ' L ' , ' M ' , ' N ' , ' O ' , ' P ' , ' Q ' , ' R ' , ' S ' , ' T ' , ' U ' , ' V ' , ' W ' , ' X ' , ' Y ' , ' Z ' };
27 private static int [] T1 = { 5 , 8 , 3 , 2 , 0 , 1 , 9 , 4 , 6 , 7 };
28 private static int [] T2 = { 4 , 5 , 3 , 2 , 7 , 0 , 8 , 9 , 1 , 6 };
29 private static int [] KeyArray1 = { 3 , 7 , 0 , 1 , 5 , 9 , 3 , 2 , 6 , 8 };
30 private static int [] KeyArray2 = { 2 , 8 , 5 , 4 , 9 , 3 , 0 , 7 , 1 , 6 };
31
32 #region 由Simon新增的四个加解密方法
33
34 #region 公共属性 静态成员 初始化DES密钥 By Simon
35
36 private static byte [] Key_64 = { 47 , 13 , 92 , 116 , 78 , 4 , 218 , 32 };
37 private static byte [] Iv_64 = { 35 , 114 , 219 , 39 , 96 , 66 , 167 , 3 };
38 private static byte [] Key_192 = { 47 , 13 , 92 , 116 , 78 , 4 , 218 , 32 , 15 , 167 , 44 , 80 , 26 , 250 , 155 , 112 , 2 , 94 , 11 , 204 , 119 , 35 , 184 , 194 };
39 private static byte [] Iv_192 = { 35 , 114 , 219 , 39 , 96 , 66 , 167 , 3 , 42 , 5 , 62 , 83 , 184 , 7 , 209 , 13 , 145 , 23 , 200 , 58 , 173 , 10 , 121 , 228 };
40 #endregion
41
42 #region 公共函数 静态成员 提供字符串MD5加密功能
43 // MD5加密,通常用在用户密码的加密和验证
44 public static string MD5_Encrypt( string val)
45 {
46 string EncryptPassword = "" ;
47 EncryptPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(val , " MD5 " );
48 return EncryptPassword;
49 }
50 #endregion
51
52 #region 公共函数 静态成员 提供字符串DES加密功能
53 // DES加密
54 public static string DES_Encrypt( string val)
55 {
56 string Code = "" ;
57 if ( ! val.Equals( "" ))
58 {
59 DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
60 MemoryStream ms = new MemoryStream();
61 CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateEncryptor(Key_64, Iv_64),CryptoStreamMode.Write);
62 StreamWriter sw = new StreamWriter(cs);
63 sw.Write(val);
64 sw.Flush();
65 cs.FlushFinalBlock();
66 ms.Flush();
67 int Length = ( int )ms.Length;
68
69 Code = Convert.ToBase64String(ms.GetBuffer(), 0 ,Length);
70 }
71 return Code;
72 }
73 #endregion
74
75 #region 公共函数 静态成员 提供字符串DES解密功能
76 // DES解密
77 public static string DES_Decrypt( string val)
78 {
79 string Code = "" ;
80 if ( ! val.Equals( "" ))
81 {
82 DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
83 byte [] buffer = Convert.FromBase64String(val);
84 MemoryStream ms = new MemoryStream(buffer);
85 CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(Key_64, Iv_64), CryptoStreamMode.Read);
86 StreamReader sr = new StreamReader(cs);
87 Code = sr.ReadToEnd();
88 }
89 return Code;
90 }
91 #endregion
92
93 #region 线性加密
94 #region 私有函数 整型 尾列加密
95 private static int Sha_End( int val)
96 {
97
98 return T1[val];
99 }
100 #endregion
101
102 #region 私有函数 整型 尾列解密
103 private static int Sha_GetEnd( int val)
104 {
105 return T2[val];
106 }
107 #endregion
108
109 #region 私有函数 整型 单步卷帘加密
110 private static int Sha_Next( int val, int pre, bool flag)
111 {
112 int result = flag ? ((val + KeyArray1[pre]) % 10 ):((val + KeyArray2[pre]) % 10 );
113 return (result + 1 ) % 10 ;
114 }
115 #endregion
116
117 #region 私有函数 整型 单步卷帘解密
118 private static int Sha_Next2( int val, int pre, bool flag)
119 {
120 int result;
121 val = (val + 9 ) % 10 ;
122 if (flag)
123 {
124 val = val >= KeyArray1[pre] ? val:val + 10 ;
125 result = val - KeyArray1[pre];
126 }
127 else
128 {
129 val = val >= KeyArray2[pre] ? val:val + 10 ;
130 result = val - KeyArray2[pre];
131 }
132 return result;
133
134 }
135 #endregion
136
137 #region 公有方法 整型 全数卷帘加密
138 public static string Line_Encrypt( int intval)
139 {
140 return Line_Encrypt(( long )intval);
141 }
142 public static string Line_Encrypt( long intval)
143 {
144 string val = intval.ToString();
145 int i;
146 string temp = "" ;
147 bool flag = true ;
148 int temp2,temp3,temp4;
149 // 先求出最后一后数
150 int pre = Sha_End(Convert.ToInt32(val.Substring(val.Length - 1 , 1 )));
151 // 从倒数第二位开始
152 temp4 = pre;
153 for (i = val.Length - 2 ;i >= 0 ;i -- )
154 {
155 // 取出该位数字
156 temp3 = Convert.ToInt32(val.Substring(i, 1 ));
157 // 算出加密码,即倒数第二位加密后放在第一位。
158 temp2 = Sha_Next(temp3,pre,flag);
159 temp += temp2;
160 pre = temp2;
161 flag =! flag;
162 }
163 return temp + temp4;
164 }
165 #endregion
166
167 #region 公有方法 整型 全数卷帘解密
168 public static string Line_Decrypt( int intval)
169 {
170 string val = intval.ToString();
171 int i;
172 string temp = "" ;
173 bool flag = true ;
174 int temp2,temp3,temp4;
175
176 // 先求出最后一后数
177 int pre = Convert.ToInt32(val.Substring(val.Length - 1 , 1 ));
178 // 从倒数第二位开始
179 temp4 = Sha_GetEnd(pre);
180 for (i = 0 ;i < val.Length - 1 ;i ++ )
181 {
182 // 取出该位数字
183 temp3 = Convert.ToInt32(val.Substring(i, 1 ));
184 // 算出加密码,即倒数第二位加密后放在第一位。
185
186 temp2 = Sha_Next2(temp3,pre,flag);
187 temp = temp2 + temp;
188 pre = temp3;
189 flag =! flag;
190 }
191 return temp + temp4;
192 }
193 #endregion
194 #endregion
195
196 #endregion // By Simon
197
198 #region MD5, 3DES encrypt and decrypt methods
199 /// <summary>
200 /// MD5加密方法
201 /// </summary>
202 /// <param name="a_strValue"> string to be encrypted </param>
203 /// <returns> encrypted string </returns>
204 public static string EncryptMD5String( string a_strValue)
205 {
206 try
207 {
208 // change to bytearray
209 Byte[] hba = ((HashAlgorithm) CryptoConfig.CreateFromName( " MD5 " )).
210 ComputeHash(StringToByteArray(a_strValue));
211
212 return ByteArrayToString(hba) ;
213 }
214 catch (Exception ex)
215 {
216 throw (ex);
217 }
218 }
219
220 /// <summary>
221 /// Judge whether or not two string are the same
222 /// </summary>
223 /// <param name="a_str1"></param>
224 /// <param name="a_str2"></param>
225 /// <returns> 比较他们是否相同 </returns>
226 public static bool IsSame( string a_str1 , string a_str2)
227 {
228 try
229 {
230 Byte[] b1 = StringToByteArray(a_str1) ;
231 Byte[] b2 = StringToByteArray(a_str2) ;
232 if (b1.Length != b2.Length)
233 {
234 return false ;
235 }
236
237 for ( int i = 0 ; i < b1.Length ; i ++ )
238 {
239 if (b1[i] != b2[i])
240 {
241 return false ;
242 }
243 }
244
245 return true ;
246 }
247 catch (Exception ex)
248 {
249 throw (ex);
250 }
251 }
252
253 /// <summary>
254 /// Convert string to Byte array
255 /// </summary>
256 /// <param name="s"> string to be converted </param>
257 /// <returns> 字符转换成ByteArray </returns>
258 public static Byte[] StringToByteArray(String s)
259 {
260 try
261 {
262 return Encoding.UTF8.GetBytes(s) ;
263 }
264 catch (Exception ex)
265 {
266 throw (ex);
267 }
268 }
269
270 /// <summary>
271 /// 转换Byte[]到字符
272 /// </summary>
273 /// <param name="a_arrByte"> Byte Array to be converted </param>
274 /// <returns> string converted from byte array </returns>
275 public static string ByteArrayToString(Byte[] a_arrByte)
276 {
277 try
278 {
279 return Encoding.UTF8.GetString(a_arrByte) ;
280 }
281 catch (Exception ex)
282 {
283 throw (ex);
284 }
285 }
286
287
288 /// <summary>
289 /// DES加密
290 /// </summary>
291 /// <param name="a_strString"> string to be encrypted </param>
292 /// <param name="a_strKey"> key </param>
293 /// <returns> string encrypted and encoded by base64 </returns>
294 /// <remarks> static method, use default ascii encode </remarks>
295 public static string Encrypt3DES( string a_strString, string a_strKey)
296 {
297 try
298 {
299 TripleDESCryptoServiceProvider DES = new
300 TripleDESCryptoServiceProvider();
301 MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
302
303 DES.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(a_strKey));
304 DES.Mode = CipherMode.ECB;
305
306 ICryptoTransform DESEncrypt = DES.CreateEncryptor();
307
308 byte [] Buffer = ASCIIEncoding.ASCII.GetBytes(a_strString);
309 return Convert.ToBase64String(DESEncrypt.TransformFinalBlock
310 (Buffer, 0 , Buffer.Length));
311 }
312 catch (Exception ex)
313 {
314 throw (ex);
315 }
316 } // end method
317
318 /// <summary>
319 /// DES加密
320 /// </summary>
321 /// <param name="a_strString"> string to be encrypted </param>
322 /// <param name="a_strKey"> key </param>
323 /// <param name="encoding"> encoding method </param>
324 /// <returns> string encrypted and encoded by base64 </returns>
325 /// <remarks> overload, assign encoding method </remarks>
326 public static string Encrypt3DES( string a_strString, string a_strKey , Encoding encoding)
327 {
328 try
329 {
330 TripleDESCryptoServiceProvider DES = new
331 TripleDESCryptoServiceProvider();
332 MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
333
334 DES.Key = hashMD5.ComputeHash(encoding.GetBytes(a_strKey));
335 DES.Mode = CipherMode.ECB;
336
337 ICryptoTransform DESEncrypt = DES.CreateEncryptor();
338
339 byte [] Buffer = encoding.GetBytes(a_strString);
340 return Convert.ToBase64String(DESEncrypt.TransformFinalBlock
341 (Buffer, 0 , Buffer.Length));
342 }
343 catch (Exception ex)
344 {
345 throw (ex);
346 }
347 }
348
349
350 /// <summary>
351 ///
352 /// </summary>
353 /// <param name="a_strString"></param>
354 /// <param name="a_strKey"></param>
355 /// <returns></returns>
356 public static string Decrypt3DES( string a_strString, string a_strKey)
357 {
358 string result = "" ;
359 try
360 {
361 TripleDESCryptoServiceProvider DES = new
362 TripleDESCryptoServiceProvider();
363 MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
364
365 DES.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(a_strKey));
366 DES.Mode = CipherMode.ECB;
367
368 ICryptoTransform DESDecrypt = DES.CreateDecryptor();
369
370 result = "" ;
371
372 byte [] Buffer = Convert.FromBase64String(a_strString);
373 result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock
374 (Buffer, 0 , Buffer.Length));
375 }
376 catch
377 {
378 // throw(new Exception("Invalid Key or input string is not a valid base64 string" , e)) ;
379 }
380
381 return result ;
382
383 } // end method
384
385 /// <summary>
386 /// DES
387 /// </summary>
388 /// <param name="a_strString"></param>
389 /// <param name="a_strKey"></param>
390 /// <param name="encoding"></param>
391 /// <returns></returns>
392 public static string Decrypt3DES( string a_strString, string a_strKey , Encoding encoding)
393 {
394 string result = "" ;
395 try
396 {
397 TripleDESCryptoServiceProvider DES = new
398 TripleDESCryptoServiceProvider();
399 MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
400
401 DES.Key = hashMD5.ComputeHash(encoding.GetBytes(a_strKey));
402 DES.Mode = CipherMode.ECB;
403
404 ICryptoTransform DESDecrypt = DES.CreateDecryptor();
405
406 result = "" ;
407
408 byte [] Buffer = Convert.FromBase64String(a_strString);
409 result = encoding.GetString(DESDecrypt.TransformFinalBlock
410 (Buffer, 0 , Buffer.Length));
411 }
412 catch (Exception e)
413 {
414 throw ( new Exception( " Invalid Key or input string is not a valid base64 string " , e)) ;
415 }
416
417 return result ;
418 } // end method
419 #endregion
420
421 #region Encrypt and Decrypt methods for Brown Puppy System
422
423 /// <summary>
424 /// Encrypt an string
425 /// </summary>
426 /// <param name="pStr"> String to be encrypted </param>
427 /// <param name="pKey"> Key string </param>
428 /// <returns></returns>
429 public string EncryptOcc( string pStr, string pKey)
430 {
431
432 string myString;
433 myString = pKey + pStr;
434 myString = TransEncrypt(myString);
435 myString = StrToAscStr(myString);
436 myString = TransEncrypt(myString);
437 myString = DecStrToHex36Str(myString);
438 myString = TransEncrypt(myString);
439 return myString;
440 }
441
442 /// <summary>
443 /// Decrypt an encrypted string
444 /// </summary>
445 /// <param name="pStr"> Encrypted string </param>
446 /// <param name="pKey"> Key string </param>
447 /// <returns></returns>
448 public string DecryptOcc( string pStr, string pKey)
449 {
450 string myString;
451
452 // HttpContext.Current.Response.Write("<hr>Now decrypt......<BR>");
453 // HttpContext.Current.Response.Flush();
454
455 myString = TransEncrypt(pStr);
456 // HttpContext.Current.Response.Write("transencrypted string:" + myString + "<BR>");
457 // HttpContext.Current.Response.Flush();
458
459 myString = Hex36StrToDecStr(myString);
460 // HttpContext.Current.Response.Write("Hex36StrToDecStr string:" + myString + "<BR>");
461 // HttpContext.Current.Response.Flush();
462
463 myString = TransEncrypt(myString);
464 // HttpContext.Current.Response.Write("transencrypted string:" + myString + "<BR>");
465 // HttpContext.Current.Response.Flush();
466
467 myString = AscStrToStr(myString);
468 // HttpContext.Current.Response.Write("AscStrToStr string:" + myString + "<BR>");
469 // HttpContext.Current.Response.Flush();
470
471 myString = TransEncrypt(myString);
472 // HttpContext.Current.Response.Write("transencrypted string:" + myString + "<BR>");
473 // HttpContext.Current.Response.Flush();
474
475 try
476 {
477 if ( ! (myString.Substring( 0 ,pKey.Length) == pKey))
478 {
479 myString = "" ;
480 }
481 myString = myString.Substring(pKey.Length);
482 }
483 catch
484 {
485 // HttpContext.Current.Response.Write("Error occurs when decrypt!<BR>");
486 myString = "" ;
487 }
488
489 return myString;
490 }
491
492
493
494 /// <summary>
495 /// Change the charaters order, for each 4-digit group, move char 1 to char 4 position, move char 2 to char 3 order.
496 /// 1234 -> 4321, ABCD -> DCBA
497 /// </summary>
498 /// <param name="pStr"></param>
499 /// <returns></returns>
500 public string TransEncrypt( string pStr)
501 {
502 string strEncrypt = "" ;
503 string c1, c2, c3, c4;
504
505 for ( int i = 0 ;i < pStr.Length;i = i + 4 )
506 {
507 c1 = "" ;
508 c2 = "" ;
509 c3 = "" ;
510 c4 = "" ;
511
512 try
513 {
514 c1 = pStr.Substring(i, 1 );
515 }
516 catch
517 {
518 }
519
520 try
521 {
522 c2 = pStr.Substring(i + 1 , 1 );
523 }
524 catch
525 {
526 }
527
528 try
529 {
530 c3 = pStr.Substring(i + 2 , 1 );
531 }
532 catch
533 {
534 }
535
536 try
537 {
538 c4 = pStr.Substring(i + 3 , 1 );
539 }
540 catch
541 {
542 }
543
544 strEncrypt = strEncrypt + c4 + c3 + c2 + c1;
545
546 }
547
548 return strEncrypt;
549 }
550
551
552 /// <summary>
553 /// Convert a string to an Ascii string, each char in the string will be convert to its ascii code.
554 /// If the ascii code is less than 100, add 0 to the left.
555 /// </summary>
556 /// <param name="pStr"></param>
557 /// <returns></returns>
558 public string StrToAscStr( string pStr)
559 {
560 string strChar;
561 byte byteChar;
562 string ascStr;
563 string strResult = "" ;
564 for ( int i = 0 ;i < pStr.Length;i ++ )
565 {
566 strChar = pStr.Substring(i, 1 );
567 byteChar = ( byte )System.Convert.ToChar(strChar);
568 if (byteChar < 100 )
569 {
570 ascStr = " 0 " + byteChar.ToString();
571 }
572 else
573 {
574 ascStr = byteChar.ToString();
575 }
576
577 strResult += ascStr;
578 }
579
580 return strResult;
581 }
582
583
584 /// <summary>
585 /// Convert an ascii code string to a string. Each 3-digit number will be treat as an ascii number
586 /// </summary>
587 /// <param name="pStr"></param>
588 /// <returns></returns>
589 public string AscStrToStr( string pStr)
590 {
591 string strResult = "" ;
592 byte ascNum;
593 if (pStr.Length % 3 != 0 )
594 {
595 return "" ;
596 }
597
598 for ( int i = 0 ;i < pStr.Length / 3 ;i ++ )
599 {
600 try
601 {
602 ascNum = System.Convert.ToByte(pStr.Substring(i * 3 , 3 ));
603 }
604 catch
605 {
606 return "" ;
607 }
608
609 strResult += System.Convert.ToChar(System.Convert.ToByte(ascNum)).ToString();
610 }
611
612 return strResult;
613 }
614
615 /// <summary>
616 /// Convert 10-based asscii number string to 36-based string
617 /// Each 3-digit number will be converted to a 36-based string
618 /// </summary>
619 /// <param name="DecStr"></param>
620 /// <returns></returns>
621 public string DecStrToHex36Str( string DecStr)
622 {
623 string strResult = "" ;
624 int intNum;
625 for ( int i = 0 ;i < DecStr.Length;i = i + 3 )
626 {
627 if (i + 3 > DecStr.Length)
628 {
629 intNum = System.Convert.ToInt32(DecStr.Substring(i,DecStr.Length - i));
630 }
631 else
632 {
633 intNum = System.Convert.ToInt32(DecStr.Substring(i, 3 ));
634 }
635
636 strResult += DecToHex36(intNum);
637 }
638
639 return strResult;
640 }
641
642 /// <summary>
643 /// Convert 36-based string to 10-based ascii number string
644 /// </summary>
645 /// <param name="Hex3Str"></param>
646 /// <returns></returns>
647 public string Hex36StrToDecStr( string Hex36Str)
648 {
649 string strResult = "" ;
650 string Hex36;
651 int intDec;
652
653 for ( int i = 0 ;i < Hex36Str.Length;i = i + 2 )
654 {
655 if (i + 2 > Hex36Str.Length)
656 {
657 Hex36 = Hex36Str.Substring(i,Hex36Str.Length - i);
658 }
659 else
660 {
661 Hex36 = Hex36Str.Substring(i, 2 );
662 }
663
664 intDec = Hex36ToDec(Hex36);
665
666 if (intDec < 10 )
667 {
668 strResult += " 00 " + intDec.ToString();
669 }
670 else if (intDec < 100 )
671 {
672 strResult += " 0 " + intDec.ToString();
673 }
674 else
675 {
676 strResult += intDec.ToString();
677 }
678 }
679
680 return strResult;
681 }
682
683 /// <summary>
684 /// Convert 36-based string to 10-based number
685 /// Only accept 2 characters string
686 /// </summary>
687 /// <param name="StrHex3"></param>
688 /// <returns></returns>
689 public int Hex36ToDec( string StrHex36)
690 {
691 int intReturn = 0 ;
692 char char1;
693 char char2;
694 if (StrHex36.Length > 2 )
695 {
696 return 0 ;
697 }
698
699 if (StrHex36.Length == 2 )
700 {
701 char1 = System.Convert.ToChar(StrHex36.Substring( 0 , 1 ));
702 char2 = System.Convert.ToChar(StrHex36.Substring( 1 , 1 ));
703 }
704 else
705 {
706 char1 = System.Convert.ToChar(StrHex36);
707 char2 = ' 0 ' ;
708 }
709
710 for ( int i = 0 ;i < arr36Base.Length;i ++ )
711 {
712 if (arr36Base[i] == char1)
713 {
714 intReturn += i * 36 ;
715 }
716 }
717
718 for ( int i = 0 ;i < arr36Base.Length;i ++ )
719 {
720 if (arr36Base[i] == char2)
721 {
722 intReturn += i;
723 }
724 }
725
726
727 return intReturn;
728
729 }
730
731 /// <summary>
732 /// Convert 10-based number to 36-based string
733 /// </summary>
734 /// <param name="tnDec"></param>
735 /// <returns></returns>
736 public string DecToHex36( int intDec)
737 {
738 string strResult = "" ;
739 int i, j;
740
741 // we only accept number less than 1000
742 if (intDec > 999 )
743 {
744 return "" ;
745 }
746
747 i = intDec / 36 ;
748 j = intDec % 36 ;
749
750 strResult = System.Convert.ToString(arr36Base[i]) + System.Convert.ToString(arr36Base[j]);
751 return strResult;
752 }
753
754
755 #endregion
756 }
757 }
758
759
760
761

 

转载于:https://www.cnblogs.com/gyweiUSTC/articles/1887104.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值