Base-64 QueryString Error
[Web Developers: ASP.NET Base64 Decryption / QueryString Problem]
The described issue comes along with Request.QueryString of encrypted strings. More specifically in combination with the ‘naughty’ “+” (plus) sign.
Here’s the assumption:
Url: /SomePage.aspx?whatsoever=zp3b4%2bTvEqk%3d
Error Message: Invalid length for a Base-64 char array.
Error Target Site: Byte[] FromBase64String(System.String)
QueryString Data:
—————–
whatsoever: zp3b4+TvEqk=
Here comes the scenario 1:
You encrypted any string which then is e.g. “zp3b4+TvEqk=”. Following you perform a HttpUtility.UrlEncode on that string to use it in your link for the SomePage.aspx page. Result of the encoding is: “zp3b4%2bTvEqk%3d”
Then the SomePage.aspx page receives the call and you perform: string s = Request.QueryString[“whatsoever”];
Naturally you feel to UrlDecode the string and pass the result then to the decryption routine. That’s exactly why you would get a n error “Invalid length for a Base-64 char array.”.
Explanation:
The Request.QueryString also receives the parameter as “zp3b4+TvEqk=”, not as “zp3b4%2bTvEqk%3d”.
If you now perform a HttpUtility.UrlDecode the “+” sign will be replaced by a blank (” “). This messes up your encrypted string so that it cannot be decrypted. Result: the error message shown above.
Just leave away the HttpUtility.UrlDecode and it should run.
Another scenario:
Assume you did not use HttpUtility.UrlEncode when you added the encrypted string to the link. In this case you got the ‘+’ sign in the URL (“zp3b4+TvEqk=”)!
That means that Request.QueryString[“wahtsoever”] will strip the ‘+’ sign away and you end up with a blank where the ‘+’ sign should be (“zp3b4 TvEqk=”). Now you could replace the blank(s) by plus sign(s) and you were fine again. Or remember scenario 1 and better UrlEncode the encrypted string before adding it to the link, because this way spares later manipulation (replacing).
Cheers, best regards,
Frank