DesAccessor.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. namespace Bowin.Common.DES
  7. {
  8. public class DesAccessor: IDesAccessor
  9. {
  10. /// <summary>
  11. /// DES加密
  12. /// </summary>
  13. /// <param name="encryptString">待加密的字符串</param>
  14. /// <param name="key">加密密钥,8倍数</param>
  15. /// <param name="iv">加密IV,8倍数</param>
  16. /// <returns></returns>
  17. public string Encrypt(string encryptString, byte[] key, byte[] iv)
  18. {
  19. //byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
  20. byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
  21. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  22. des.Mode = CipherMode.ECB;
  23. des.Padding = PaddingMode.PKCS7;
  24. MemoryStream mStream = new MemoryStream();
  25. CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
  26. cStream.Write(inputByteArray, 0, inputByteArray.Length);
  27. cStream.FlushFinalBlock();
  28. return Convert.ToBase64String(mStream.ToArray());
  29. }
  30. /// <summary>
  31. /// DES解密
  32. /// </summary>
  33. /// <param name="decryptString">待解密的字符串</param>
  34. /// <param name="key">解密密钥,要求为8位,和加密密钥相同</param>
  35. /// <param name="iv">解密IV,要求为8位,和加密密钥相同</param>
  36. /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
  37. public string Decrypt(string decryptString, byte[] key, byte[] iv)
  38. {
  39. try
  40. {
  41. //byte[] rgbKey = Encoding.UTF8.GetBytes(Key);
  42. byte[] inputByteArray = Convert.FromBase64String(decryptString);
  43. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  44. des.Mode = CipherMode.ECB;
  45. des.Padding = PaddingMode.PKCS7;
  46. MemoryStream mStream = new MemoryStream();
  47. CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Write);
  48. cStream.Write(inputByteArray, 0, inputByteArray.Length);
  49. cStream.FlushFinalBlock();
  50. return Encoding.UTF8.GetString(mStream.ToArray());
  51. }
  52. catch
  53. {
  54. return "";
  55. }
  56. }
  57. public string DeDesToken(DesModel desModel)
  58. {
  59. byte[] vi = new byte[8];
  60. var dk = "MMmmHHss";
  61. vi = Encoding.UTF8.GetBytes("00000000");
  62. byte[] key = Encoding.UTF8.GetBytes(desModel.tm.ToString(dk));
  63. return Decrypt(desModel.token, key, vi);
  64. }
  65. }
  66. }