Padding is invalid and cannot be removed

In this post I’m looking at the Padding is invalid and cannot be removed error

Background on Padding is invalid and cannot be removed

Today I tried to send data encrypted between an application built in c# and an application built in Silverlight. When I encrypted the data in one application the decryption would fail with the following exception:

An exception of type ‘System.Security.Cryptography.CryptographicException’ occurred in mscorlib.dll but was not handled in user code Additional information: Padding is invalid and cannot be removed

Your Solution

To encrypt my plain text I used the following code:

public static string EncryptStringAES(string plainText, string sharedSecret) {

  string outStr = null;
  AesManaged aesAlg = null;
  try
  {
   Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); 
   aesAlg = new AesManaged(); 
   aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); 
   aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8); 
   ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); 
   using (MemoryStream msEncrypt = new MemoryStream())
   {
      using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
      {
         using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
         {
            swEncrypt.Write(plainText);
         }
      } 
      outStr = Convert.ToBase64String(msEncrypt.ToArray());
   }
  } 
  finally {
    if (aesAlg != null) aesAlg.Clear();
  }
  return outStr;
}

for the decryption I used this bit of code:

public static string DecryptStringAES(string cipherText, string sharedSecret)

{
AesManaged aesAlg = null; string plaintext = null; try {
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
aesAlg = new AesManaged();
aesAlg.BlockSize = aesAlg.LegalBlockSizes[0].MaxSize;
aesAlg.KeySize = aesAlg.LegalKeySizes[0].MaxSize;
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
byte[] bytes = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(bytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
if (aesAlg != null) aesAlg.Clear();
}
  return plaintext;
}

only after setting the block size and the key size the error went away.

2 thoughts on “Padding is invalid and cannot be removed

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 4,909 other subscribers

Recent Posts

Archive

Thank you for visiting SharePains