Monthly Archives: April 2014

Passing a small object in the querystring

For the current project at work I need to pass some information from an application or website to another website. Rather than storing the state in a database I decided to serialize the state object and pass it, encrypted, in the querystring.

This is the encoding function:


Dim plaintext as String = myState.Serialize
Dim bytes As Byte() = ASCIIEncoding.UTF8.GetBytes(plaintext)
Dim encrypted As Byte() = Encryption.Encrypt(bytes, key)
Dim encodedtext As String = Convert.ToBase64String(encrypted)
Return System.Web.HttpUtility.UrlEncode(encodedtext)

Note that the serialized and encrypted object is url encoded using the System.Web.HttpUtility.

This is the decode function:


Dim decodedtext As Byte() = Convert.FromBase64String(querystring)
Dim decrypted As Byte() = Encryption.Decrypt(decodedtext, key)
Dim plaintext As String = ASCIIEncoding.UTF8.GetString(decrypted)
Dim mystate As New State
mystate.Deserialize(plaintext)
Return mystate

and in C# because I need to practice my skills:


byte[] decodedtext = Convert.FromBase64String(querystring);
byte[] decrypted = Encryption.Decrypt(decodedtext, key);
string plaintext = ASCIIEncoding.UTF8.GetString(decrypted);
State mystate = new State();
mystate.Deserialize(plaintext);
return mystate;

Note that the querystring is not url decoded, this is because the ASP.NET http handler decodes the querystring before it is passed to your code.