C# AES加密解密
1 public static string Encrypt(string key, string clearText) 2 { 3 byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); 4 using (Aes encryptor = Aes.Create()) 5 { 6 Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64 }); 7 encryptor.Key = pdb.GetBytes(32); 8 encryptor.IV = pdb.GetBytes(16); 9 using (MemoryStream ms = new MemoryStream()) 10 { 11 using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) 12 { 13 cs.Write(clearBytes, 0, clearBytes.Length); 14 cs.Close(); 15 } 16 clearText = Convert.ToBase64String(ms.ToArray()); 17 } 18 } 19 return clearText; 20 } 21 public static string Decrypt(string key, string cipherText) 22 { 23 cipherText = cipherText.Replace(" ", "+"); 24 byte[] cipherBytes = Convert.FromBase64String(cipherText); 25 using (Aes encryptor = Aes.Create()) 26 { 27 Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64 }); 28 encryptor.Key = pdb.GetBytes(32); 29 encryptor.IV = pdb.GetBytes(16); 30 using (MemoryStream ms = new MemoryStream()) 31 { 32 using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) 33 { 34 cs.Write(cipherBytes, 0, cipherBytes.Length); 35 cs.Close(); 36 } 37 cipherText = Encoding.Unicode.GetString(ms.ToArray()); 38 } 39 } 40 return cipherText; 41 }