Monday, January 7, 2013

AES encryption error

When implementing symmetric encryption in an application, I had some trouble specifying the correct key size.
public string Encrypt(string plainText, string key = KEY, string IV = IV)
{
 byte[] encrypted;
 // Create an Aes object
 // with the specified key and IV.
 using (Aes aesAlg = Aes.Create())
 {
  aesAlg.Key = System.Text.Encoding.Default.GetBytes(key);
  aesAlg.IV = System.Text.Encoding.Default.GetBytes(IV);

  // Create a decrytor to perform the stream transform.
  ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

  // Create the streams used for encryption.
  using (var msEncrypt = new MemoryStream())
  using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
  {
   using (var swEncrypt = new StreamWriter(csEncrypt))
   {
                       //Write all data to the stream.
                       swEncrypt.Write(plainText);
   }
   encrypted = msEncrypt.ToArray();
  }
 }

 // Return the encrypted bytes from the memory stream.
 return Convert.ToBase64String(encrypted);
}


I tried some possible key values but I always got the following error back:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Security.Cryptography.CryptographicException: The specified key is not a valid size for this algorithm.


   at System.Security.Cryptography.AesCryptoServiceProvider.set_Key(Byte[] value)

   --- End of inner exception stack trace ---

   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
   at System.Reflection.Assembly.CreateInstance(String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
 
So what is a correct length for the key and vector when using AES encryption?
For the key and vector specify a 16 characters long value.

2 comments:

sarah nelson said...
This comment has been removed by a blog administrator.
Perry Joel said...
This comment has been removed by a blog administrator.