title: Using AESManaged with byte arrays
body: <p>I am trying to implement an in-memory AESManaged encrypt/decrypt. The code here is based on this:</p>
  
  <p><a href="https://stackoverflow.com/questions/9237324/encrypting-decrypting-large-files-net">Encrypting/Decrypting large files (.NET)</a></p>
  
  <p>The encrypt part seems to work, that is, there are no exceptions. But the decrypt part throws an "index was outside the bounds of the array" error.</p>
  
  <p>In earlier code the transform is initialize like this:</p>
  
  <pre><code> aes = new AesManaged();
   aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
   aes.KeySize = aes.LegalKeySizes[0].MaxSize;            
   Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(Key, salt, 1);
   aes.Key = key.GetBytes(aes.KeySize / 8);
   aes.IV = key.GetBytes(aes.BlockSize / 8);
   aes.Mode = CipherMode.CBC;
   transform = aes.CreateDecryptor(aes.Key, aes.IV);
  
  
  void AESDecrypt(ref byte[] inB)
  {
      using (MemoryStream destination = new MemoryStream(inB, 0, inB.Length))
      {
          using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
              {
                  try
                  {
                      using (MemoryStream source = new MemoryStream(inB, 0, inB.Length))
                      {
                          if (source.CanWrite==true)
                          {
                              source.Write(inB, 0, inB.Length);
                              source.Flush(); //&lt;&lt;inB is unchanged by the write
                          }
                      }
                  }
                  catch (CryptographicException exception)
                  {
                      if (exception.Message == "Padding is invalid and cannot be removed.")
                          throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
                      else
                          throw;
                  }
              }
          } &lt;====At this point I get an IndexOutofBounds exception.
      }
  }
  </code></pre>
  
  <p>It seems that the offending line may be: 
       using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))</p>