title: Missing last half of bytes when decrypting using AES in .NET
body: <p>I'm attempting to implement some encryption of data in .NET with a user supplied password. As I understand this, I encrypt the file with a symetric key, and encrypt this key with another key that is generated by the user. This means that a password change does not require a change to the data, just an update to the encrypted key.</p>
  <p>When testing out the AES functions, I can encrypt my 256 bit key, but when decrypting I only get the first 16 bytes back from .NET:</p>
  <pre class="lang-cs prettyprint-override"><code>public static byte[] Salt = new byte[64];
  public static byte[] IV = new byte[16];
  public static string Password1 = &quot;PWD&quot;;
  public static byte[] Key = new byte[32];
  
  static void Main(string[] args)
  {
      Salt = RandomNumberGenerator.GetBytes(64);
      IV = RandomNumberGenerator.GetBytes(16);
      Key = RandomNumberGenerator.GetBytes(32);
      var pwdK1 = RandomNumberGenerator.GetBytes(32);
  
      byte[] aKey1 = new byte[32];
      byte[] bKey1 = new byte[32];
  
      using (Aes aes = Aes.Create())
      {
          aes.Mode = CipherMode.CBC;
          aes.Key = pwdK1;        //use key generated by user pwd
          aes.IV = IV;
  
          var str = new MemoryStream(Key);
  
          using (var crypStr = new CryptoStream(str, aes.CreateEncryptor(), CryptoStreamMode.Read))
          {
              int i = crypStr.Read(aKey1, 0, 32);
          }
      }
  
      using (Aes aes = Aes.Create())
      {
          aes.Mode = CipherMode.CBC;
          aes.Key = pwdK1;        //use key generated by user pwd
          aes.IV = IV;
  
          var str = new MemoryStream(aKey1);
  
          using (var crypStr = new CryptoStream(str, aes.CreateDecryptor(), CryptoStreamMode.Read))
          {
              int i = crypStr.Read(bKey1, 0, 32);
              var p = bKey1.ToArray();
          }
      }
      //we should have Key in p/bKey1, but we only have the first 16 bytes of Key.
  }
  </code></pre>
  <p>Here, <code>pwdK1</code> is actually generated using a 3rd party <code>Argon2</code> library, code modified for this post.</p>
  <p>The key and IV used are the same, the mode is the same, but when reading out the decrypted key in the decrypt stage, I only see the first 16 bytes that I see in <code>Key</code> stored in variable <code>p</code>. For the first <code>crypStr.Read</code> I get a full 32 bytes returned, but the decrypt Read returns only 16 bytes in i. The remaining 16 bytes are all 0.</p>
  <p>Any ideas what I could be doing wrong?</p>