Server.URLEncode an Encrypted String - do it twice my friend!!

Query string is a very important part of a web application which needs to be prevented from being sniffed or changed when it carries sensitive data. We do not have a magic wand that upon waving will hide the sensitive portion of the query string across multiple requests, but we do have powerful encryption algorithms that come as a rescue and encrypt everything which turns out to look like a toddler's handwriting. And, if it contains characters that are prohibited in a query string e.g. ('+','?',':','&','/','='), then we can encode it using Server.URLEncoding API which comes as part of .NET class library.

var encryptedString = CommonUtils.Encrypt("clientid=1980&code=alphabravo", lKey);
var encodedEncrypted = Server.URLEncode(encryptedString);

In the above code, CommonUtils is my homegrown encryption utility (symmetric key encryption) that takes lKey to encrypt/decrypt large quantities of data. But wait, I notice it's throwing an exception on the receiving side and not showing my properly URLEncoded query string that i generated while sending. Why o why!!

After a small research I found that I need to do Server.URLEncoding twice but not just once before sending it out. By just doing it once, I witnessed that all my URL encoded characters for ('+') were getting lost somehow. Anyways, the final correct sequence that I have come to know about encoding an encrypted string and decoding it is this:
  1. Encrypt it
  2. Encode it twice
  3. Decode it once
  4. Decrypt it
Happy coding!!

0 comments:

Post a Comment