using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace DPumpHydr.WinFrmUI.WenSkin.AES { public class AesEnDe { public static string key = "qw6HjFG2HCZOIl0LXxt4UDofqN0RP5qi"; public static string vector = "frhNcbk53xSzKsgf"; /// /// 加密 /// /// /// public static string AESEncrypt(string data) { return AESEncrypt(data, key, vector); } /// /// 解密 /// /// /// public static string AESDecrypt(string data) { return AESDecrypt(data, key, vector); } /// /// AES加密 /// /// 被加密的明文 /// 密钥 /// 向量 /// 密文 public static string AESEncrypt(string Data, string Key, string Vector) { byte[] plainBytes = Encoding.UTF8.GetBytes(Data); byte[] bKey = new byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); byte[] bVector = new byte[16]; Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length); byte[] Cryptograph = null; // 加密后的密文 Rijndael Aes = Rijndael.Create(); try { // 开辟一块内存流 using MemoryStream Memory = new MemoryStream(); // 把内存流对象包装成加密流对象 using CryptoStream Encryptor = new CryptoStream(Memory, Aes.CreateEncryptor(bKey, bVector), CryptoStreamMode.Write); // 明文数据写入加密流 Encryptor.Write(plainBytes, 0, plainBytes.Length); Encryptor.FlushFinalBlock(); Cryptograph = Memory.ToArray(); } catch { return null; } return Convert.ToBase64String(Cryptograph); } /// /// AES解密 /// /// 被解密的密文 /// 密钥 /// 向量 /// 明文 public static string AESDecrypt(string Data, string Key, string Vector) { byte[] original = null; // 解密后的明文 try { byte[] encryptedBytes = Convert.FromBase64String(Data); byte[] bKey = new byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); byte[] bVector = new byte[16]; Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length); Rijndael Aes = Rijndael.Create(); // 开辟一块内存流,存储密文 using MemoryStream Memory = new MemoryStream(encryptedBytes); // 把内存流对象包装成加密流对象 using CryptoStream Decryptor = new CryptoStream(Memory, Aes.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read); // 明文存储区 using MemoryStream originalMemory = new MemoryStream(); byte[] Buffer = new byte[1024]; int readBytes = 0; while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0) { originalMemory.Write(Buffer, 0, readBytes); } original = originalMemory.ToArray(); } catch { return null; } return Encoding.UTF8.GetString(original); } } }