title: Why can't I set AES KeySize in C#?
body: <p>In the following function(C#), the default value of KeySize is 128, if i don't set any value into KeySize, this function can work fine, the encrypted result would be as same as what I prediceted. But if I set 128 into KeySize, which is as same as the default value, then the result would be unpredictable. I set same input data, but the result would changed each time. I really have no idea what's going on.(p.s. I also tried 192, still work as same situation.)</p>
  <pre><code>using System;
  using System.IO;
  using System.Security.Cryptography;    
  
  private static byte[] AesEncrypt(byte[] keys, byte[] iv, byte[] data, int size)
  {
      using Aes aesAlg = Aes.Create();
      aesAlg.Key = keys;
      aesAlg.IV = iv;
      if (size != 0)
      {
          aesAlg.KeySize = size;
      }
      ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
      using MemoryStream msEncrypt = new MemoryStream();
      using CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
      csEncrypt.Write(data, 0, data.Length);
      byte[] encrypted = msEncrypt.ToArray();
      csEncrypt.FlushFinalBlock();
      return encrypted;
  }
  </code></pre>