tags:

views:

2062

answers:

2

I'm encrypting and Base64 a string. Everything works great, until I retrieve the encrypted string from the QueryString collection. The Encrypted text contains a plus symbol. When I retrieve the encrypted string, where a plus once was there is now a space. As you can imagine this doesn't decrypt.

I have tried both Server.HtmlEncode/HtmlDecode and Server.UrlEncode/Server.UrlDecode with no avail. Both methods confuse the plus symbol with the space.

Any idea's?

Here is a similar post: QueryString Malformed

Edit: I found the solution: Server.UrlEncode does work, I was applying Server.UrlDecode and didn't need too.

+1  A: 

I had problems like you few years ago. Here's my code to decode base64 query string to string and vise versa

 public static String DoDecryption(String Value)
 {
  Decryptor dec = new Decryptor(EncryptionAlgorithm.TripleDes );
  dec.IV = Encoding.ASCII.GetBytes("funky");
  byte [] DecValue =  Convert.FromBase64String(Value.Replace("+++","=="));
  byte [] DecKey   = Encoding.ASCII.GetBytes("0123456789012345");
  byte [] DecipherValue = dec.Decrypt(DecValue,DecKey);
  return Encoding.ASCII.GetString(DecipherValue);
 }

and here is the encryption part

 public static String DoEncryption(String Value)
 {
  Encryptor enc = new Encryptor(EncryptionAlgorithm.TripleDes);
  byte [] EncValue =  Encoding.ASCII.GetBytes(Value);
  byte [] EncKey   = Encoding.ASCII.GetBytes("0123456789012345");
  enc.IV = Encoding.ASCII.GetBytes("funky");
  byte [] CipherValue = enc.Encrypt(EncValue,EncKey);
  //InitVector = Encoding.ASCII.GetString(enc.IV);
  return Convert.ToBase64String(CipherValue).Replace("==","+++");
 }

Note that Value parameter in DoEncryption is the string you want to encrypt into querystring and value parameter in DoDecryption is query string that already convert into base64 string.

Hope thats help

Funky81
Hope that's help
Funky81
I added another answer. Be careful with this as "+++" is valid in the middle of an encrypted string.
cisellis
+4  A: 

Be careful, the method of substituting "+++" for "==" is dangerous because in rare situations, it is possible for an encrypted query string to validly contain "+++". In this case, the decryption fails. For a better solution to the problem, look at using the "modified base64 for url". It involves switching out "-" for "+" and "_" for "/" and has no "==" padding. It seems to be working for us, even in situations where the other failed. Here is the link I used for reference that is working for us.

http://stackoverflow.com/questions/1228701/code-for-decoding-encoding-a-modified-base64-url

cisellis
Thanks for the follow up.
Chuck Conway