0

I'm using (or attempting to!) the code for encrypting/decrypting a string found in this post Encrypting & Decrypting a String in C#.

If I call the functions directly, i.e.

StringHelper sHelp = new StringHelper();

var encryptMe = sHelp.EncryptString("comahony@centlaw.com", "myPassphrase"); 

Returns /sx3sL4DE7sM2klGKN3V+CQKdP02ZxbVxANjDh2yfGo= which is perfect

and if I then call

var decryptMe = sHelp.DecryptString(encryptMe, "myPassphrase");

Returns comahony@centlaw.com which again is what I'm after.

But if I pass the encrypted string on parameter on the querystring. i.e.

http://localhost:12345/sso?c=/sx3sL4DE7sM2klGKN3V+CQKdP02ZxbVxANjDh2yfGo=

and call the decryption function using:

var decryptMe = sHelp.DecryptString(Request.QueryString["c"].ToString(), "myPassphrase");

I'm getting the error of "Invalid length for a Base-64 char array or string."

From digging around on the net it appears to be something to do with the parameter needing to be URLEncoded but try as I might I just can't get past this error.

Could something shed some light please?

Thanks, C

Community
  • 1
  • 1
SxChoc
  • 619
  • 3
  • 10
  • 26
  • Have you debugged to see the value of `Request.QueryString["c"].ToString()`? maybe its just plain wrong. I can't help you if I don't know the input – EpicKip Apr 12 '17 at 13:47
  • Base64 can contain + and / characters which can have special meaning when present in a query string you should pre/post substitute them with other characters. – Alex K. Apr 12 '17 at 13:50
  • Possible duplicate of [How to achieve Base64 URL safe encoding in C#?](http://stackoverflow.com/questions/26353710/how-to-achieve-base64-url-safe-encoding-in-c) – Alex K. Apr 12 '17 at 13:50
  • `+` has a special meaning in URLs. That's why there are URL specific [variants of Base 64](https://en.wikipedia.org/wiki/Base64#Variants_summary_table) – Damien_The_Unbeliever Apr 12 '17 at 13:50
  • Right right, so basically I need encrypt the string and replace the special characters (/ +) before it's appended to the QS and then replace the special characters before de-encrypting it. – SxChoc Apr 12 '17 at 14:27
  • "Replace", use HttpUtility.UrlEncode/UrlDecode, but yes, just don't handroll the replacement, use the built in methods for this. – Lasse V. Karlsen Aug 23 '23 at 12:59

0 Answers0