Solved

Error in Rijndael:  padding is invalid and cannot be removed

Posted on 2014-11-27
8
1,806 Views
Last Modified: 2014-11-27
I'm trying to encrypt/decrypt a file with the managed net crypto class: RijndaelManaged

First I didn't set the padding and could write the data then read the data correctly with the correct password.  I then tested with an incorrect password and got the error (exception) message in the title:
padding is invalid and cannot be removed

Some searching later and found that I ought to set the padding mode.  I have done that (
RMCrypto.Padding = PaddingMode.PKCS7;

Open in new window

)
Still same error with an incorrect password.

More searching and found the recommendation to use FlushFinalBlock.  Done that just before closing the cryptographic stream.  Now on reading I get that error even with the correct password but the data has been decrypted correctly.

What am I doing wrong?
0
Comment
Question by:AndyAinscow
  • 4
  • 2
  • 2
8 Comments
 
LVL 32

Accepted Solution

by:
sarabande earned 250 total points
ID: 40468943
I assume you already visited stackoverflow.com/questions/8583112/padding-is-invalid-and-cannot-be-removed

if I read answer 6 from atconway correctly, the error message 'padding-is-invalid-and-cannot-be-removed' also shows up if using different keys for encryption and decryption. so it is a bug and your code was good.

Sara
0
 
LVL 44

Author Comment

by:AndyAinscow
ID: 40468974
Hi Sara.  I've read various posts about this and all seem to say the following that the error message is due to an incorrect password.
I would have expected that decrypting with an incorrect password would still run smoothly, just result in garbage in the decrypted data - not an exception being thrown when closing the stream.  

CryptoStream cs = new CryptoStream(fs, ....  
where fs is a filestream, same construct used in both encrytion and decryption streams


Are you saying that an exception on stream closure is by design when the password to decrypt is not the same as the encrypt password ?
0
 
LVL 61

Expert Comment

by:btan
ID: 40469071
The padding should be part of the encryption as well as decryption. the flush should also be performed. Actually you may also consider Padding=PaddingMode.none; as a try out
https://www.simple-talk.com/blogs/2012/02/28/oh-no-my-paddings-invalid/

Some even stated "When you give the Encrypt/Decrypt functions an empty string" this error msg also appear, you can also check it sample http://www.vbforums.com/showthread.php?748943-Padding-is-invalid-and-cannot-be-removed
0
 
LVL 44

Author Comment

by:AndyAinscow
ID: 40469118
I've tried various PaddingModes and do use the FlushFinalBlock before closing the writing stream.
>>I found out that this error happens when you give the Encrypt/Decrypt functions an empty string
from the vbforums link.  Hmmm.  There are some empty strings being encrypted - the data is structured so some parts are empty strings.  I'll give it a try with data that doesn't have any empty strings and if it behaves then there is a smoking gun at that point.  It'll be a while before I can do that test, I'll post an update in a few hours time.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 61

Assisted Solution

by:btan
btan earned 250 total points
ID: 40469159
other useful sharing
https://social.msdn.microsoft.com/Forums/vstudio/en-US/d1788582-bf8c-43ec-a686-49647c359136/unexplained-cryptographicexception-padding-is-invalid?forum=netfxbcl
I did find one other issue with me code in case anyone else has this issue, I was trying to read directly from a file into a cryptostream and that doesn't work because you are giving the length as the file size, and that doesn't leave room for the padding.
I resolved this issue by remembering to limit the size of the MemoryStream created from the byte array. See the code below. The second and third argument to the MemoryStream constructor were missing in my original code, and adding them solved my problem.
0
 
LVL 44

Author Comment

by:AndyAinscow
ID: 40469387
I've got absolutely nowhere.  :-(
I removed empty strings in the test data - still same behaviour.
I've changed various settings until I ran out of ideas of what to change - ho hum.
I changed the data to just one string - it threw an exception on decrypting with the wrong password.
It really does look like this is a 'feature' of the .net classes, at least as I am using them.

The good news is that I can build in exception handling to identify an incorrect password.
0
 
LVL 32

Expert Comment

by:sarabande
ID: 40469447
I looked thru samples and actually found no other way how an error could be indicated beside throwing an exception. it is strange that the exception was not thrown before closure (I would have thought that when creating the decryptor a wrong key could be detected) but probably this is not possible as there is no input data available at this time. so it is well possible that wrong keys could not be detected before end of decryption (at dispose time I would guess) what would explain the behavior.

Sara
0
 
LVL 44

Author Comment

by:AndyAinscow
ID: 40469492
I can understand not throwing an error at the start (unless the key was included in the encrypted data at the start - which might not be a good idea).  What surprises me is it erroring at the end of the decryption when closing the cryptostream (I don't see anything in the documentation about that) rather than finishing without error but just resulting in garbage in the data.  The algorithm is block based - so the size of the output file is 'fixed' to a block multiple - which is what the padding mode is used for.

(I had intended on including a short but unique string identifier at a known location to check if the decrypt had succeeded or had failed with an incorrect password.)


ps.  I could be using it incorrectly so if anyone is certain (code snippet that functions please) that it does not result in an exception with an incorrect password then the question can be re-opened and further investigated.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Envision that you are chipping away at another e-business site with a team of pundit developers and designers. Everything seems, by all accounts, to be going easily.
SSL stands for “Secure Sockets Layer” and an SSL certificate is a critical component to keeping your website safe, secured, and compliant. Any ecommerce website must have an SSL certificate to ensure the safe handling of sensitive information like…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now