Contact   HugeTiger.com Home   Goods & Services   Secure   Professional   Web Email

HugeTiger.com

Subject: Answer: AesCryptoServiceProvider Error: Padding is invalid and cannot be removed. C#

Date: 1/20/2012

Hi

I started with code from msdn which worked fine.

Then I started to change some things for fun. I changed the key size to 128 bits, and the feedback size also to 128 bits. I'm still using the only block size of 128 bits and the default CipherMode.CBC. The Cipher Block Chaining (CBC) uses feedback.

All still good. The round trip text exactly matches the clear text.

I also used Convert.ToBase64String to write byte[ ] arrays to a human readable string in a log file.

Or if you prefer you can use ASCIIEncoding and BitConverter.ToString.

I wrote things such as the key the IV and the cipher text

Then using RNGCryptoServiceProvider I generated my own Key and IV instead of using the defaults from AesCryptoServiceProvider

All still good

As expected, although the clear text remained exactly the same, the cipher text completely changed from run to run.

If I hold the clear text, key and IV constant, then the cipher text is also constant.

If I use eIV for encryption and dIV for decryption then the first block of the round trip text is mangled. This was unexpected, I thought the entire round trip text would be mangled since we were using Cipher Block Chaining (CBC).

If I use eIV=dIV and eKey = dkey all is good.

However, if I changed just one bit of dkey, I expected all of the round trip text to be mangled. I never found out if this was the case because I got:

Error: Padding is invalid and cannot be removed.

occurred on line: plaintext = srDecrypt.ReadToEnd();

I also tried:  int Len = srDecrypt.Peek() and got the same error.

In conclusion "Error: Padding is invalid and cannot be removed." can be caused by a discrepancy between the eKey and the dKey.

An underlying cause may be an Exception is raised when attempting to decode a byte outside of the ASCII range which is U+0000 to U+007F.

The wrong decryption key will most likely generate bytes outside of this range.


 
 

Email:  Phone: 808-372-1570

John Orendt, PO Box 8601 Honolulu Hawaii 96830-0601 United States of America
Home  Contact Blackjack Burn Database Explorer Donate e-commerce Free Secure Message Service Free Web Hosting Memory Mats Products and Services  Submit for You  Testimonials  Tetris  Website Design Web Hosting Social Intelligence End of Day Trader Hugetiger Copyright © 2012

bottom