DesTool.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #region DESEnCode DES加密     
  17. public static string Encrypt(string pToEncrypt, string sKey)
  18. {
  19. // string pToEncrypt1 = HttpContext.Current.Server.UrlEncode(pToEncrypt);     
  20. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  21. byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);
  22. //建立加密对象的密钥和偏移量      
  23. //原文使用ASCIIEncoding.ASCII方法的GetBytes方法      
  24. //使得输入密码必须输入英文文本      
  25. des.Key = Encoding.ASCII.GetBytes(sKey);
  26. des.IV = Encoding.ASCII.GetBytes(sKey);
  27. MemoryStream ms = new MemoryStream();
  28. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  29. cs.Write(inputByteArray, 0, inputByteArray.Length);
  30. cs.FlushFinalBlock();
  31. StringBuilder ret = new StringBuilder();
  32. foreach (byte b in ms.ToArray())
  33. {
  34. ret.AppendFormat("{0:X2}", b);
  35. }
  36. ret.ToString();
  37. return ret.ToString();
  38. }
  39. #endregion
  40. #region DESDeCode DES解密     
  41. public static string Decrypt(string pToDecrypt, string sKey)
  42. {
  43. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  44. byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
  45. for (int x = 0; x < pToDecrypt.Length / 2; x++)
  46. {
  47. int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
  48. inputByteArray[x] = (byte)i;
  49. }
  50. des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  51. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  52. MemoryStream ms = new MemoryStream();
  53. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  54. cs.Write(inputByteArray, 0, inputByteArray.Length);
  55. cs.FlushFinalBlock();
  56. StringBuilder ret = new StringBuilder();
  57. return System.Text.Encoding.Default.GetString(ms.ToArray());
  58. }
  59. #endregion
  60. }
  61. }