/V5_WinLibs/Core/DESHelper1.cs

https://github.com/lsamu/V5_DataCollection · C# · 82 lines · 59 code · 7 blank · 16 comment · 1 complexity · 7ce63e3672641ab30266e5c5425a7569 MD5 · raw file

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. namespace V5_WinLibs.Core {
  8. /// <summary>
  9. /// Des¶Ô³Æ¼ÓÃÜ ½âÃÜ
  10. /// </summary>
  11. public class DESHelper1 {
  12. #region ========¼ÓÃÜ========
  13. /// <summary>
  14. /// DES¼ÓÃÜ·½·¨
  15. /// </summary>
  16. /// <param name="strPlain">Ã÷ÎÄ</param>
  17. /// <param name="strDESKey">ÃÜÔ¿</param>
  18. /// <param name="strDESIV">ÏòÁ¿ Ö»ÄÜ8λ</param>
  19. /// <returns>ÃÜÎÄ</returns>
  20. public static string Encrypt(string source, string _DESKey) {
  21. StringBuilder sb = new StringBuilder();
  22. using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) {
  23. byte[] key = ASCIIEncoding.ASCII.GetBytes(_DESKey);
  24. byte[] iv = ASCIIEncoding.ASCII.GetBytes(_DESKey);
  25. byte[] dataByteArray = Encoding.UTF8.GetBytes(source);
  26. des.Mode = System.Security.Cryptography.CipherMode.CBC;
  27. des.Key = key;
  28. des.IV = iv;
  29. string encrypt = "";
  30. using (MemoryStream ms = new MemoryStream())
  31. using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) {
  32. cs.Write(dataByteArray, 0, dataByteArray.Length);
  33. cs.FlushFinalBlock();
  34. foreach (byte b in ms.ToArray()) {
  35. sb.AppendFormat("{0:X2}", b);
  36. }
  37. encrypt = sb.ToString();
  38. }
  39. return encrypt;
  40. }
  41. }
  42. #endregion
  43. #region ========½âÃÜ========
  44. /// <summary>
  45. /// ½âÃÜÊý¾Ý
  46. /// </summary>
  47. /// <param name="Text">¼ÓÃܵÄ×Ö·û´®</param>
  48. /// <param name="sKey">¼ÓÃÜKey Ö»ÄÜ8λ</param>
  49. /// <returns></returns>
  50. public static string Decrypt(string Text, string sKey) {
  51. try {
  52. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  53. int len;
  54. len = Text.Length / 2;
  55. byte[] inputByteArray = new byte[len];
  56. int x, i;
  57. for (x = 0; x < len; x++) {
  58. i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
  59. inputByteArray[x] = (byte)i;
  60. }
  61. des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  62. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  63. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  64. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  65. cs.Write(inputByteArray, 0, inputByteArray.Length);
  66. cs.FlushFinalBlock();
  67. return Encoding.UTF8.GetString(ms.ToArray());
  68. }
  69. catch (Exception) {
  70. return string.Empty;
  71. }
  72. }
  73. #endregion
  74. }
  75. }