2008/11/04

Encode Query String by using Base64 (6/24/2009 updated)

Recently, I read a post about encrypting the Query String, and it's quite interested. You can read it here. However, we can use a simpler way to do the same thing like this:
public static string EncryptString(string toEncode)
{
  try
  {
    byte[] toEncodeAsBytes = Encoding.UTF8.GetBytes(toEncode);
    return Convert.ToBase64String(toEncodeAsBytes);
  }
  catch (Exception ex)
  {
    //do your error handling here
  }
}

public static string DecryptString(string toDecrypt)
{
  try
  {
    byte[] encodedDataAsBytes = Convert.FromBase64String(toDecrypt.Replace(" ", "+"));
    return Encoding.UTF8.GetString(encodedDataAsBytes);
  }
  catch (Exception ex)
  {
    //do your error handling here
  }
}

You can apply some other encryption algorithms like TripleDES before applying the Base64 encoding.

PS: Be careful of the URL length restriction.

No comments:

Post a Comment