DESEncryptor.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. namespace Long.Utils.Encryptor;
  4. /// <summary>
  5. /// DES加密器:用于加密和解密字符串
  6. /// </summary>
  7. public class DESEncryptor
  8. {
  9. private const string _defaultKey = "Long";
  10. private static byte[] _rgbIV = new byte[8] { 2, 4, 8, 16, 32, 64, 128, 255 };
  11. /// <summary>
  12. /// 加密
  13. /// </summary>
  14. /// <param name="data">数据</param>
  15. /// <param name="key">密钥</param>
  16. /// <returns>加密结果字符串</returns>
  17. public static string Encrypt(string data, string key = _defaultKey)
  18. {
  19. if (data == null || string.IsNullOrEmpty(data.Trim()))
  20. {
  21. return string.Empty;
  22. }
  23. try
  24. {
  25. byte[] bytes = Encoding.UTF8.GetBytes(key.Substring(0, key.Length > 8 ? 8 : key.Length).PadRight(8, '0'));
  26. var des = DES.Create();
  27. byte[] bytes2 = Encoding.UTF8.GetBytes(data);
  28. MemoryStream memoryStream = new MemoryStream();
  29. CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(bytes, _rgbIV), CryptoStreamMode.Write);
  30. cryptoStream.Write(bytes2, 0, bytes2.Length);
  31. cryptoStream.FlushFinalBlock();
  32. return Convert.ToBase64String(memoryStream.ToArray());
  33. }
  34. catch (Exception ex)
  35. {
  36. Console.WriteLine(ex.Message);
  37. return string.Empty;
  38. }
  39. }
  40. /// <summary>
  41. /// 解密
  42. /// </summary>
  43. /// <param name="data">数据</param>
  44. /// <param name="key">密钥</param>
  45. /// <returns>解密结果字符串</returns>
  46. public static string Decrypt(string data, string key = _defaultKey)
  47. {
  48. if (data == null || string.IsNullOrEmpty(data.Trim()))
  49. {
  50. return string.Empty;
  51. }
  52. try
  53. {
  54. byte[] bytes = Encoding.UTF8.GetBytes(key.Substring(0, key.Length > 8 ? 8 : key.Length).PadRight(8, '0'));
  55. var des = DES.Create();
  56. byte[] array = Convert.FromBase64String(data);
  57. MemoryStream memoryStream = new MemoryStream();
  58. CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(bytes, _rgbIV), CryptoStreamMode.Write);
  59. cryptoStream.Write(array, 0, array.Length);
  60. cryptoStream.FlushFinalBlock();
  61. return Encoding.UTF8.GetString(memoryStream.ToArray());
  62. }
  63. catch (Exception ex)
  64. {
  65. Console.WriteLine(ex.Message);
  66. return string.Empty;
  67. }
  68. }
  69. }