DESEncrypt.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. using System.IO;
  5. namespace LogService
  6. {
  7. public class DESEncrypt
  8. {
  9. /// <summary>
  10. /// DESEncrypt加密解密算法。
  11. /// </summary>
  12. private DESEncrypt()
  13. {
  14. //
  15. // TODO: 在此处添加构造函数逻辑
  16. //
  17. }
  18. private static string key = "znf_2018";
  19. /// <summary>
  20. /// 对称加密解密的密钥
  21. /// </summary>
  22. public static string Key
  23. {
  24. get
  25. {
  26. return key;
  27. }
  28. set
  29. {
  30. key = value;
  31. }
  32. }
  33. /// <summary>
  34. /// DES加密
  35. /// </summary>
  36. /// <param name="encryptString"></param>
  37. /// <returns></returns>
  38. public static string DesEncrypt(string encryptString)
  39. {
  40. byte[] keyBytes = Encoding.UTF8.GetBytes(key);
  41. byte[] keyIV = keyBytes;
  42. byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
  43. DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
  44. MemoryStream mStream = new MemoryStream();
  45. CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
  46. cStream.Write(inputByteArray, 0, inputByteArray.Length);
  47. cStream.FlushFinalBlock();
  48. return Convert.ToBase64String(mStream.ToArray());
  49. }
  50. /// <summary>
  51. /// DES解密
  52. /// </summary>
  53. /// <param name="decryptString"></param>
  54. /// <returns></returns>
  55. public static string DesDecrypt(string decryptString)
  56. {
  57. byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
  58. byte[] keyIV = keyBytes;
  59. byte[] inputByteArray = Convert.FromBase64String(decryptString);
  60. DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
  61. MemoryStream mStream = new MemoryStream();
  62. CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
  63. cStream.Write(inputByteArray, 0, inputByteArray.Length);
  64. cStream.FlushFinalBlock();
  65. return Encoding.UTF8.GetString(mStream.ToArray());
  66. }
  67. }
  68. }