4

I get the following exception in some cases through (decryption) , and i can't recognize exactly the reason :

Invalid length for a Base-64 char array

My Code :

public static string encodeSTROnUrl(string thisEncode)
{
  if (null == thisEncode)
      return string.Empty;

  return HttpUtility.UrlEncode(Encrypt(thisEncode));
}


// string thisDecode = "3Dn%2bsJJPXprU4%3d"; //this is the value which cause the exception.
public static string decodeSTROnUrl(string thisDecode)
{
   return Decrypt(HttpUtility.UrlDecode(thisDecode));
}


QueryStringEncryption.Cryptography.decodeSTROnUrl(Request.QueryString["val"].ToString());

The exact line which throw the exception is :

 Byte[] byteArray = Convert.FromBase64String(text);

I thought i fix this problem by encoding and decoding before and after the encryption and the decryption operation.but some values still throw this exception .


Note: i note some strange behavior : the id as a query string sent to my mail is : n%2bsJJPXprU4%3d and it works without exceptions ..

and the user who has the problem the sent url contains 3Dn%2bsJJPXprU4%3d

is this a browser problem ??!!

Anyname Donotcare
  • 11,113
  • 66
  • 219
  • 392
  • Can you post your entire code for `Encrypt` and `Decrypt`? Most likely you are doing some inappropriate encoding conversions (ASCII, Unicode) in between. – vgru Jun 04 '12 at 09:07
  • The whole code in this link : http://stackoverflow.com/questions/4555249/invalid-length-for-a-base-64-char-array-during-decoding-decryption – Anyname Donotcare Jun 04 '12 at 09:10

2 Answers2

8

Decoding the querystring values is done already when it's parsed into the Request. try without 'HttpUtility.UrlDecode'

public static string decodeSTROnUrl(string thisDecode)
    {
        return Decrypt(thisDecode);
    }
Damith
  • 62,401
  • 13
  • 102
  • 153
4

The 64-bit encoding has problems with spaces in the string. Try to add the following after encrypting

sEncryptedString = sEncryptedString.Replace(' ', '+');
Blachshma
  • 17,097
  • 4
  • 58
  • 72
  • Unless a space and a plus sign represent the same character for OP, that's hardly the right solution. – vgru Jun 04 '12 at 09:05
  • @just_name, updated the response, I remembered it incorrectly. You need to change the encrypted result... OR (even better) right BEFORE you decrypt – Blachshma Jun 04 '12 at 09:09
  • 3
    The point is not to avoid the exception, but to decode the exact string you originally encoded, and this will not do it. – vgru Jun 04 '12 at 09:12