DESExtensions.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. namespace Hotline.Tools
  4. {
  5. public static class DESExtensions
  6. {
  7. private const string key = "fwayfway";
  8. /// <summary>
  9. /// 加密
  10. /// </summary>
  11. /// <param name="text"></param>
  12. /// <returns></returns>
  13. public static string Encrypt(string text)
  14. {
  15. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  16. byte[] inputByteArray;
  17. inputByteArray = Encoding.Default.GetBytes(text);
  18. des.Key = ASCIIEncoding.ASCII.GetBytes(key);
  19. des.IV = ASCIIEncoding.ASCII.GetBytes(key);
  20. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  21. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  22. cs.Write(inputByteArray, 0, inputByteArray.Length);
  23. cs.FlushFinalBlock();
  24. StringBuilder ret = new StringBuilder();
  25. foreach (byte b in ms.ToArray())
  26. {
  27. ret.AppendFormat("{0:X2}", b);
  28. }
  29. return ret.ToString();
  30. }
  31. /// <summary>
  32. /// 解密
  33. /// </summary>
  34. /// <param name="text"></param>
  35. /// <returns></returns>
  36. public static string Decrypt(string text)
  37. {
  38. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  39. int len;
  40. len = text.Length / 2;
  41. byte[] inputByteArray = new byte[len];
  42. int x, i;
  43. for (x = 0; x < len; x++)
  44. {
  45. i = Convert.ToInt32(text.Substring(x * 2, 2), 16);
  46. inputByteArray[x] = (byte)i;
  47. }
  48. des.Key = ASCIIEncoding.ASCII.GetBytes(key);
  49. des.IV = ASCIIEncoding.ASCII.GetBytes(key);
  50. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  51. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  52. cs.Write(inputByteArray, 0, inputByteArray.Length);
  53. cs.FlushFinalBlock();
  54. return Encoding.Default.GetString(ms.ToArray());
  55. }
  56. }
  57. }