开发者

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

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?


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 :)


By using TrimEnd() like this:

theString.TrimEnd("/0");


You could prefix the length of the string to the beginning of the string before encrypting them both, then, after decrypting, use the length to determine where the string ends.

Or you could base64 encode the string before encrypting it, then decode it afterwards.

Or encode it using a binary or XML serializer before encrypting it.

All of these methods have the advantage that they allow you to recover exactly the string that was stored. Any method that takes the current output and guesses at what transformation to apply does not have that property.


I don't see what it has to do with encryption. IIUC you're already done decrypting and have a plaintext string that has something at the end you want to remove. If so, your question is about string manipulation and it's irrelevant what encryption algorithm you're using. But maybe I misunderstood..?

Suggestion (probably not correct, but you'll get the idea):

string pattern = (i % 2 == 0? "/0" : "0/");
var sb = new StringBuilder(s);

int i = s.Length - 1;
while (sb[i] == pattern[i % 2]) --i;
sb.Length = i;
s = sb.ToString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜