DesTool.cs 2.9 KB

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