1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks;
namespace Utils { public static class AES { public const string AesKey = "AES"; public static string AESDecrypt(String Data, String Key = AesKey) { return Encoding.UTF8.GetString(AESDecrypt(Convert.FromBase64String(Data), Key));
} public static string AESEncrypt(String Data, String Key = AesKey) { return Convert.ToBase64String(AESEncrypt(Encoding.UTF8.GetBytes(Data), Key)); }
public static byte[] AESEncrypt(byte[] Data, String Key = AesKey) { MemoryStream mStream = new MemoryStream(); RijndaelManaged aes = new RijndaelManaged();
byte[] plainBytes = Data; Byte[] bKey = new Byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; aes.KeySize = 128; aes.Key = bKey; CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write); try { cryptoStream.Write(plainBytes, 0, plainBytes.Length); cryptoStream.FlushFinalBlock(); return mStream.ToArray(); } finally { cryptoStream.Close(); mStream.Close(); aes.Clear(); } }
public static byte[] AESDecrypt(byte[] Data, String Key = AesKey) { Byte[] encryptedBytes = Data; Byte[] bKey = new Byte[32]; Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length); MemoryStream mStream = new MemoryStream(encryptedBytes); RijndaelManaged aes = new RijndaelManaged(); aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; aes.KeySize = 128; aes.Key = bKey; CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read); try { byte[] tmp = new byte[encryptedBytes.Length + 32]; int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32); byte[] ret = new byte[len]; Array.Copy(tmp, 0, ret, 0, len); return ret; } finally { cryptoStream.Close(); mStream.Close(); aes.Clear(); } } } }
|