DesTool.cs 2.4 KB

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