DesBuilder.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 PackingPress.Common
  9. {
  10. public class DesBuilder
  11. {
  12. private const string EncryptKey = "V1NN0KEY";
  13. private static readonly byte[] Keys = { 0x56, 0x34, 0x90, 0xCD, 0xEF, 0xAB, 0x12, 0x78 };
  14. /// <summary>
  15. /// 加密
  16. /// </summary>
  17. /// <param name="value"></param>
  18. /// <returns></returns>
  19. public static string Encrypt(string value)
  20. {
  21. if (string.IsNullOrEmpty(value)) return string.Empty;
  22. try
  23. {
  24. byte[] rgbKey = Encoding.UTF8.GetBytes(EncryptKey);
  25. byte[] rgbIv = Keys;
  26. byte[] inputByteArray = Encoding.UTF8.GetBytes(value);
  27. var dCsp = new DESCryptoServiceProvider();
  28. using (var stream = new MemoryStream())
  29. {
  30. using (var cStream = new CryptoStream(stream, dCsp.CreateEncryptor(rgbKey, rgbIv), CryptoStreamMode.Write))
  31. {
  32. cStream.Write(inputByteArray, 0, inputByteArray.Length);
  33. cStream.FlushFinalBlock();
  34. var output = Convert.ToBase64String(stream.ToArray());
  35. return "{" + output + "}";
  36. }
  37. }
  38. }
  39. catch
  40. {
  41. return value;
  42. }
  43. }
  44. /// <summary>
  45. /// 解密
  46. /// </summary>
  47. /// <param name="value"></param>
  48. /// <returns></returns>
  49. public static string Decrypt(string value)
  50. {
  51. if (string.IsNullOrEmpty(value)) return string.Empty;
  52. try
  53. {
  54. value = value.Substring(1, value.Length - 2);
  55. byte[] rgbKey = Encoding.UTF8.GetBytes(EncryptKey);
  56. byte[] rgbIv = Keys;
  57. byte[] inputByteArray = Convert.FromBase64String(value);
  58. var dcsp = new DESCryptoServiceProvider();
  59. using (var stream = new MemoryStream())
  60. {
  61. using (var cStream = new CryptoStream(stream, dcsp.CreateDecryptor(rgbKey, rgbIv), CryptoStreamMode.Write))
  62. {
  63. cStream.Write(inputByteArray, 0, inputByteArray.Length);
  64. cStream.FlushFinalBlock();
  65. return Encoding.UTF8.GetString(stream.ToArray());
  66. }
  67. }
  68. }
  69. catch
  70. {
  71. return value;
  72. }
  73. }
  74. }
  75. }