So, last week we were beating our heads against a wall trying to figure out why we could not decrypt encrypted XML files supplied by our client along with the decryption algorithm.
We tried to rewrite the decryption method, researched the Rijndael Cryptography, tried other test files. We even encrypted our own files and then decrypted them with ease… so the decryption works. But, no matter what we did, we got the following error trying to decrypt the client supplied files:
System.Security.Cryptography.CryptographicException was unhandled
Length of the data to decrypt is invalid.
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at Decryptor.Program.Decode(Byte[] data) in C:\Projects\Decryptor\Program.cs:line 85
at Decryptor.Program.Main(String[] args) in C:\Projects\
Decryptor\Program.cs:line 17
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Unfortunately, this error is not very descriptive and there are tons of blogs on Google containing developers with the same error but a totally different problem… Eventually, after bumping heads back and fourth, my client and I finally discovered the issue.
When he sent the files to me, he FTP’d them to his desktop, then emailed them to me. I wanted to eliminate all the possibilities of error and asked him to use his webmail to send me the files directly from the server and Voila! It worked! After further digging, we realized it was the FTP process that he hadn’t previously told me about. Since the files still had an “xml” extension, the FTP client transferred them in ASCII mode. This caused the encrypted data to get corrupted and therefore it could not be decrypted. Encrypted files MUST be transmitted in Binary mode over FTP. There are two ways to assure this: set your FTP client from “Auto” to “Binary” under its transfer options -OR- give the encrypted xml file a different extension like “exml” or “encxml”. Most FTP clients will fall back to binary if they don’t recognize the file extension, but your best bet is to always force Binary.
I hope this saves somebody the extra time and research it cost us! 🙂