RijndaelManaged Decryption - How can I remove the padding /0 gracefully?

Hcabnettek picture Hcabnettek · Mar 10, 2011 · Viewed 7.8k times · Source

How can I remove the padding from a decrypted string? I'm using RijndaelManaged provider to encrypt and decrypt. When I decrypt there are several /0/0/0/0/0/0 at the end of the string. My question is how can I gracefully (properly) remove the characters from the result string?

Answer

Morten Mertner picture Morten Mertner · Mar 10, 2011

You are most likely not using the correct padding and block modes of the RijndaelManaged instance (called provider in the code below). Since the symmetric encryption providers in .NET are all block ciphers, these settings affect how padding works (as well as how secure the output will be).

The settings below will give you the best security when using RijndaelManaged:

// set the padding algorithm
provider.Padding = PaddingMode.ISO10126; // default is PKCS7
// set the block chaining mode
provider.Mode = CipherMode.CBC;

If you are not the one encrypting the data and you cannot figure out which settings the originating party used then you'll find help in some of the other answers :)