Invalid space and cannot be removed?

I watched online what this exception means with respect to my program, but cannot find a solution or a reason why this happens with my particular program. I used the example provided by my msdn to encrypt and decrypt an XmlDocument using the Rijndael algorithm. Encryption works fine, but when I try to decrypt, I get the following exception:

Filling is invalid and cannot be deleted

Can someone tell me what I can do to solve this problem? My code below is where I get the key and other data. If cryptoMode is false, it will call the decryption method in which the exception occurs:

public void Cryptography(XmlDocument doc, bool cryptographyMode) { RijndaelManaged key = null; try { // Create a new Rijndael key. key = new RijndaelManaged(); const string passwordBytes = "Password1234"; //password here byte[] saltBytes = Encoding.UTF8.GetBytes("SaltBytes"); Rfc2898DeriveBytes p = new Rfc2898DeriveBytes(passwordBytes, saltBytes); // sizes are devided by 8 because [ 1 byte = 8 bits ] key.IV = p.GetBytes(key.BlockSize/8); key.Key = p.GetBytes(key.KeySize/8); if (cryptographyMode) { Ecrypt(doc, "Content", key); } else { Decrypt(doc, key); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { // Clear the key. if (key != null) { key.Clear(); } } } private void Decrypt(XmlDocument doc, SymmetricAlgorithm alg) { // Check the arguments. if (doc == null) throw new ArgumentNullException("Doc"); if (alg == null) throw new ArgumentNullException("alg"); // Find the EncryptedData element in the XmlDocument. XmlElement encryptedElement = doc.GetElementsByTagName("EncryptedData")[0] as XmlElement; // If the EncryptedData element was not found, throw an exception. if (encryptedElement == null) { throw new XmlException("The EncryptedData element was not found."); } // Create an EncryptedData object and populate it. EncryptedData edElement = new EncryptedData(); edElement.LoadXml(encryptedElement); // Create a new EncryptedXml object. EncryptedXml exml = new EncryptedXml(); // Decrypt the element using the symmetric key. byte[] rgbOutput = exml.DecryptData(edElement, alg); <---- I GET THE EXCEPTION HERE // Replace the encryptedData element with the plaintext XML element. exml.ReplaceData(encryptedElement, rgbOutput); } 
+84
c # cryptography
Dec 20 2018-11-21T00:
source share
12 answers

Rijndael / AES is a block cipher. It encrypts data in 128-bit (16-character) blocks. Cryptographic padding is used to ensure that the last message block is always the correct size.

Your decryption method expects whatever its default insert is, and does not find it. As @NetSquirrel says, you need to explicitly set padding for encryption and decryption. Unless you have a reason to do otherwise, use PKCS # 7 indentation.

+60
Dec 21 '11 at 12:56 on
source share

Make sure that the keys you use for encryption and decryption are the same . The padding method, even if it is not explicitly set, should still allow proper decryption / encryption (if not installed, they will be the same). However, if for some reason you use a different set of keys for decryption than is used for encryption, you will get this error:

Filling is invalid and cannot be deleted

If you use some kind of algorithm to dynamically generate keys that will not work. They must be the same for encryption and decryption. One common way is for the caller to provide keys in the constructor of the encryption method class to prevent the encryption / decryption process with either hand while creating these elements. It focuses on the task (data encryption and decryption) and requires the caller to invoke iv and key .

+35
Jul 31 '13 at 16:08
source share

In the interest of finding people, it may be appropriate to verify that the input is decrypted. In my case, the information sent for decryption was (erroneously) included as an empty string. This led to a fill error.

This may relate to the rossum answer, but was considered worth mentioning.

+21
Aug 28 '13 at 15:08
source share

The service times of the battle, I finally solved the problem.
(Note: I use standard AES as a symmetric algorithm. For everyone.)

  • Change the algorithm class. Replace the RijndaelManaged class with an AESManaged one.
  • Do not set an explicit set of KeySize algorithm classes, leaving them by default.
    (This is a very important step. I think there is an error in the KeySize property.)



Here is the list you want to check which argument you might have skipped:

  • Key
    (an array of bytes, the length must be exactly one of 16, 24, 32 bytes for a different key size.)
  • IV
    (byte array, 16 bytes)
  • Ciphermode
    (One of CBC, CFB, CTS, ECB, OFB)
  • Paddingmode
    (One of ANSIX923, ISO10126, None, PKCS7, Zeros)
+8
Feb 19 '16 at 9:42 on
source share

If the same key and initialization vector are used for encoding and decoding, this problem is not associated with decoding data, but with encoding data.

After you call the Write method on the CryptoStream object, you should ALWAYS call the FlushFinalBlock method before the Close method.

The MSDN documentation on the CryptoStream.FlushFinalBlock method states:
"Calling the Close method will call FlushFinalBlock ..."
https://msdn.microsoft.com/en-US/library/system.security.cryptography.cryptostream.flushfinalblock(v=vs.110).aspx
This is not true. Calling the Close method simply closes the CryptoStream and the output stream.
If you do not call FlushFinalBlock before Close after writing the data for encryption, then when decrypting the data, calling the Read or CopyTo method for your CryptoStream object will raise a CryptographicException (message: "Filling is not allowed and cannot be deleted").

This is probably true for all encryption algorithms derived from SymmetricAlgorithm (Aes, DES, RC2, Rijndael, TripleDES), although I just checked this for AesManaged and MemoryStream as the output stream.

So, if you get this CryptographicException during decryption, read the value of the Stream Length output property after you write your data for encryption, then call FlushFinalBlock and read its value again. If it has changed, you know that calling FlushFinalBlock is NOT mandatory.

And you do not need to do any additions programmatically or choose a different value for the Padding property. Filling is a method of the FlushFinalBlock method.

.........

Additional note for Kevin:

Yes, CryptoStream calls FlushFinalBlock before calling Close, but it's too late: when the CryptoStream Close method is called, the output stream also closes.

If your output stream is a MemoryStream, you cannot read its data after closing it. Therefore, you need to call FlushFinalBlock on your CryptoStream before using encrypted data written to a MemoryStream.

If your output stream is FileStream, things are worse because recording is buffered. As a result, the last bytes written may not be written to the file if you close the output stream before calling Flush for FileStream. Therefore, before calling Close for CryptoStream, you must first call FlushFinalBlock for your CryptoStream, and then call Flush for your FileStream.

+5
Nov 12 '16 at 15:04
source share

My problem was that passPhrase encryption did not match passPhrase decryption ... so it threw this error .. a little misleading.

+2
Jan 25 '17 at 15:00
source share

Another scenario, again for finding people.

For me, this error occurred during the Dispose () method, which masked the previous error, not related to encryption.

As soon as another component was fixed, this exception disappeared.

0
Jul 14 '15 at 2:31 on
source share

I ran into this padding error when I manually edited the encrypted lines in the file (using notepad) because I wanted to check how the decryption function would work if I had the encrypted content manually changed.

The solution for me was to post

  try decryption stuff.... catch inform decryption will not be carried out. end try 

As I said, my fill error was due to the fact that I manually typed over the decrypted text using notepad. Perhaps my answer will help you with the decision.

0
Feb 13 '16 at 19:25
source share

The solution that fixed mine was that I accidentally used different keys for encryption and decryption methods.

0
Mar 09 '17 at 15:01
source share

I had the same error. In my case, this was because I saved the encrypted data in an SQL database. The table in which the data is stored has a binary (1000) data type. When extracting data from the database, it decrypts these 1000 bytes, while there are actually 400 bytes. Thus, removing the final zero (600) from the result solved the problem.

0
Feb 22 '18 at 9:00
source share

I had this error, and I explicitly set the block size: aesManaged.BlockSize = 128;

As soon as I removed it, it worked.

0
Jan 22 '19 at 21:04
source share

I encountered this error while trying to transfer the unencrypted file path to the decryption method. The solution was to check if the transferred file was encrypted before trying to decrypt

 if (Sec.IsFileEncrypted(e.File.FullName)) { var stream = Sec.Decrypt(e.File.FullName); } else { // non-encrypted scenario } 
-5
Jan 09 '18 at 17:15
source share



All Articles