2014-12-06 82 views
0

我試圖讓這個AES示例代碼工作。但是我沒有收到任何返回到我的cipherText變量的東西。我沒有得到錯誤,只是沒有返回。我在這裏做錯了什麼?AES加密器不能正常工作

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; 
       } 
      } 
     } 
    }; 


} 

回答

3

三個選項,所有這些都做同樣的事情,

要麼調用csEncrypt.Close()或使用csEncrypt.FlushFinalBlock()刷新加密數據到內存流 - cipertext = msEncrypt.ToArray()之前調用它。

或者,將cipher = msEncrypt.ToArray(); return cipertext;移到要寫入密碼流的使用塊之外。

csEncrypt.Flush()這可能是第一個猜測什麼都不做..

http://reflector.webtropy.com/default.aspx/DotNET/DotNET/[email protected]/untmp/whidbey/REDBITS/ndp/clr/src/BCL/System/Security/Cryptography/[email protected]/1/[email protected]

public override void Flush() 
{ 
    return; 
}