DesTool.cs 2.4 KB

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