/AzyleeCC.Utils/AzyleeCC.Core/DataUtils/EncryptUtils/DesTool.cs

https://github.com/yuzhengyang/Fork · C# · 80 lines · 49 code · 9 blank · 22 comment · 1 complexity · 9b1725c8e2632141cffa38c42b9f4212 MD5 · raw file

  1. //************************************************************************
  2. // author: yuzhengyang
  3. // date: 2018.3.27 - 2018.6.3
  4. // desc: Des 加密解密工具
  5. // Copyright (c) yuzhengyang. All rights reserved.
  6. //************************************************************************
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Security.Cryptography;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. namespace AzyleeCC.Core.DataUtils.EncryptUtils
  15. {
  16. public class DesTool
  17. {
  18. /// <summary>
  19. /// DESEnCode DES加密
  20. /// </summary>
  21. /// <param name="pToEncrypt"></param>
  22. /// <param name="sKey"></param>
  23. /// <returns></returns>
  24. public static string Encrypt(string pToEncrypt, string sKey)
  25. {
  26. // string pToEncrypt1 = HttpContext.Current.Server.UrlEncode(pToEncrypt);     
  27. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  28. byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);
  29. //建立加密对象的密钥和偏移量      
  30. //原文使用ASCIIEncoding.ASCII方法的GetBytes方法      
  31. //使得输入密码必须输入英文文本      
  32. des.Key = Encoding.ASCII.GetBytes(sKey);
  33. des.IV = Encoding.ASCII.GetBytes(sKey);
  34. MemoryStream ms = new MemoryStream();
  35. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  36. cs.Write(inputByteArray, 0, inputByteArray.Length);
  37. cs.FlushFinalBlock();
  38. StringBuilder ret = new StringBuilder();
  39. foreach (byte b in ms.ToArray())
  40. {
  41. ret.AppendFormat("{0:X2}", b);
  42. }
  43. ret.ToString();
  44. return ret.ToString();
  45. }
  46. /// <summary>
  47. /// DESDeCode DES解密
  48. /// </summary>
  49. /// <param name="pToDecrypt"></param>
  50. /// <param name="sKey"></param>
  51. /// <returns></returns>
  52. public static string Decrypt(string pToDecrypt, string sKey)
  53. {
  54. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  55. byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
  56. for (int x = 0; x < pToDecrypt.Length / 2; x++)
  57. {
  58. int i = (Convert.ToInt32(pToDecrypt.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. MemoryStream ms = new MemoryStream();
  64. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  65. cs.Write(inputByteArray, 0, inputByteArray.Length);
  66. cs.FlushFinalBlock();
  67. StringBuilder ret = new StringBuilder();
  68. return System.Text.Encoding.Default.GetString(ms.ToArray());
  69. }
  70. }
  71. }