AES加密器无法正常工作

我试图让这个AES示例代码正常工作。 但是我没有得到任何返回我的cipherText变量的内容。 我没有得到错误,只是没有回复。 我在这做错了什么?

public byte[] key { get; set; } public byte[] IV { get; set; } public byte[] ciphertext { get; set; } public string plainText { get; set; } public byte[] Encrypt(string InputPlaintext) { InputPlaintext = "attack at dawn"; using (AesCryptoServiceProvider AESEncryptor = new AesCryptoServiceProvider()) { ////using the AesCryptoServiceProvider to generate the IV and Key key = AESEncryptor.Key; IV = AESEncryptor.IV; ICryptoTransform encryptor = AESEncryptor.CreateEncryptor(key, IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(InputPlaintext); ciphertext = msEncrypt.ToArray(); return ciphertext; } } } }; } 

三个选项,所有这些都做同样的事情,

调用csEncrypt.Close()或使用csEncrypt.FlushFinalBlock()将加密数据刷新到内存流 – 在cipertext = msEncrypt.ToArray()之前调用它。

或者,移动cipher = msEncrypt.ToArray(); return cipertext; cipher = msEncrypt.ToArray(); return cipertext; 在您正在写入加密流的使用块之外。

注意csEncrypt.Flush()可能是第一次猜测什么都没做..

http://reflector.webtropy.com/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/clr/src/BCL/System/Security/Cryptography/CryptoStream@cs/1/CryptoStream@ CS

 public override void Flush() { return; }