using System.Security.Cryptography; using System.Text; namespace Long.Utils.Encryptor; /// /// DES加密器:用于加密和解密字符串 /// public class DESEncryptor { private const string _defaultKey = "Long"; private static byte[] _rgbIV = new byte[8] { 2, 4, 8, 16, 32, 64, 128, 255 }; /// /// 加密 /// /// 数据 /// 密钥 /// 加密结果字符串 public static string Encrypt(string data, string key = _defaultKey) { if (data == null || string.IsNullOrEmpty(data.Trim())) { return string.Empty; } try { byte[] bytes = Encoding.UTF8.GetBytes(key.Substring(0, key.Length > 8 ? 8 : key.Length).PadRight(8, '0')); var des = DES.Create(); byte[] bytes2 = Encoding.UTF8.GetBytes(data); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(bytes, _rgbIV), CryptoStreamMode.Write); cryptoStream.Write(bytes2, 0, bytes2.Length); cryptoStream.FlushFinalBlock(); return Convert.ToBase64String(memoryStream.ToArray()); } catch (Exception ex) { Console.WriteLine(ex.Message); return string.Empty; } } /// /// 解密 /// /// 数据 /// 密钥 /// 解密结果字符串 public static string Decrypt(string data, string key = _defaultKey) { if (data == null || string.IsNullOrEmpty(data.Trim())) { return string.Empty; } try { byte[] bytes = Encoding.UTF8.GetBytes(key.Substring(0, key.Length > 8 ? 8 : key.Length).PadRight(8, '0')); var des = DES.Create(); byte[] array = Convert.FromBase64String(data); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(bytes, _rgbIV), CryptoStreamMode.Write); cryptoStream.Write(array, 0, array.Length); cryptoStream.FlushFinalBlock(); return Encoding.UTF8.GetString(memoryStream.ToArray()); } catch (Exception ex) { Console.WriteLine(ex.Message); return string.Empty; } } }