Encrypt and Decrypt Query String

Hmanjarawala
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 11216 red flag
Rating: 4.75 out of 5  
 4 vote(s)

In this article we will get an idea, about how to encode query string while information passing and how to decode it at the receiver end.

Introduction

In our development routine many time we need to pass information from one page to another. Most popular way to do this is to pass Query String along with url. But as we all know, it’s not safe as it’s visible to user. Here is a solution.

Objective

Pass information through encoded Query String and decode it on second page.


Using the code

In this example, I have developed a helper class, that contains method for encrypting and decrypting Query string.

I’m using TripleDES algorithm which using MD5 generated hash as a sault. Code for same is given below.

// The Querystring to encrypt.

string Msg = Request.QueryString;

string Password = "Pa5sw0rd";

 

string EncryptedString = MySample.EncryptString(Msg, Password);


Response.Redirect("Default2.aspx?" + EncryptedString);

And on Receiver Page.

string EncodedQueryString = Response.RawURL.Substring(Response.RawURL.IndexOf("?") +1 );

string QryString  = MySample.DecryptString(QryString, Password);

In the EncryptString function, we apply the TripleDES algorithm with a 128 bit key. But first we need to turn the above passphrase (‘Pa5sw0rd’) into a 128 bit key. One useful coincidence is that the MD5 hash algorithm accepts a set of bytes of any length and turns them into a 128 bit hash. So by running the password through the MD5 hashing algorithm we create our key.

 

// Step 1. We hash the passphrase using MD5

// We use the MD5 hash generator as the result is a 128 bit byte array

// which is a valid length for the TripleDES encoder we use below

 

MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

 

The TripleDES algorithm itself turns a byte array into an encrypted byte array. So we first need to convert our C# message string (which is Unicode encoded) into a byte array through the System.Text.UTF8Encoding encoder.

 

The key is used to initialize the TripleDES algorithm. In addition we need to specify that we will only encode something once (CipherMode.ECB) and because its unlikely that our source string fits into a single TripleDES block we need to specify how we want to pad any remaining bytes (PaddingMode.PKCS7).

 

// Step 2. Create a new TripleDESCryptoServiceProvider object

TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

 

// Step 3. Setup the encoder

TDESAlgorithm.Key = TDESKey;

TDESAlgorithm.Mode = CipherMode.ECB;

TDESAlgorithm.Padding = PaddingMode.PKCS7;

 

The encrypted byte array is finally converted into a Base64 encoded string for easy storage. The DecryptString function is very similar to the encryption function, except that it turns the Base64 encoded encrypted message back into the original UTF8 string.

Decryption process is exactly revers of the what we did at a time of encryption.

before decrypt string user has to set same setting which he/she has done at a time of enctryption. i.e. follow the same step like:

// Step 1. We hash the passphrase using MD5

// We use the MD5 hash generator as the result is a 128 bit byte array

// which is a valid length for the TripleDES encoder we use below


MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));


// Step 2. Create a new TripleDESCryptoServiceProvider object

TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();


// Step 3. Setup the decoder

TDESAlgorithm.Key = TDESKey;

TDESAlgorithm.Mode = CipherMode.ECB;

TDESAlgorithm.Padding = PaddingMode.PKCS7;


After setting these setting Convert Base64 encoded message to original UTF8 string

// Step 4. Convert the input string to a byte[]

byte
[] DataToDecrypt = Convert.FromBase64String(Message);


Finally Decrypt this cipher byte to plain byte.

Complete code is given below.

using System;

using System.Text;

using System.Security.Cryptography;

 

namespace EncryptStringSample

{

    class MySample

    {

 

        public static string EncryptString(string Message, string Passphrase)

        {

            byte[] Results;

            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

 

            // Step 1. We hash the passphrase using MD5

            // We use the MD5 hash generator as the result is a 128 bit byte array

            // which is a valid length for the TripleDES encoder we use below

 

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

 

            // Step 2. Create a new TripleDESCryptoServiceProvider object

            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

 

            // Step 3. Setup the encoder

            TDESAlgorithm.Key = TDESKey;

            TDESAlgorithm.Mode = CipherMode.ECB;

            TDESAlgorithm.Padding = PaddingMode.PKCS7;

 

            // Step 4. Convert the input string to a byte[]

            byte[] DataToEncrypt = UTF8.GetBytes(Message);

 

            // Step 5. Attempt to encrypt the string

            try

            {

                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();

                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);

            }

            finally

            {

                // Clear the TripleDes and Hashprovider services of any sensitive information

                TDESAlgorithm.Clear();

                HashProvider.Clear();

            }

 

            // Step 6. Return the encrypted string as a base64 encoded string

            return Convert.ToBase64String(Results);

        }

 

        public static string DecryptString(string Message, string Passphrase)

        {

            byte[] Results;

            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

 

            // Step 1. We hash the passphrase using MD5

            // We use the MD5 hash generator as the result is a 128 bit byte array

            // which is a valid length for the TripleDES encoder we use below

 

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

 

            // Step 2. Create a new TripleDESCryptoServiceProvider object

            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

 

            // Step 3. Setup the decoder

            TDESAlgorithm.Key = TDESKey;

            TDESAlgorithm.Mode = CipherMode.ECB;

            TDESAlgorithm.Padding = PaddingMode.PKCS7;

 

            // Step 4. Convert the input string to a byte[]

            byte[] DataToDecrypt = Convert.FromBase64String(Message);

 

            // Step 5. Attempt to decrypt the string

            try

            {

                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();

                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);

            }

            finally

            {

                // Clear the TripleDes and Hashprovider services of any sensitive information

                TDESAlgorithm.Clear();

                HashProvider.Clear();

            }

 

            // Step 6. Return the decrypted string in UTF8 format

            return UTF8.GetString(Results);

        }

    }

}



Conclusion


From above article, it's more clear how to send encoded Querystring.

Page copy protected against web site content infringement by Copyscape

About the Author

Hmanjarawala
Full Name: Himanshu Manjarawala
Member Level: Bronze
Member Status: Member
Member Since: 7/30/2011 7:42:18 AM
Country: India
Himanshu Manjarawala Sr. Software Engineer@AutomationAnywhere http://fieredotnet.wordpress.com/
http://himanshumbri.blogspot.com
I am Himanshu Manjarawala, Graduate in Computer Science and MCA From Veer Narmad South Gujarat University, Surat Gujarat India. Currently working as Sr. Software Developer in Automation Anywhere.

Login to vote for this post.

Comments or Responses

Posted by: Samarmir on: 4/3/2012 | Points: 25
very nice article.
Thanks.
Posted by: Goelanant on: 10/25/2012 | Points: 25
thanks for the article.
We are currently implementing a feature where we pass across some information on the query string to the other parties and i am planning to use this technique. Initially we thought of using of asymmetric encryption but that proved to be a nightmare as different teams have different way of generating the private key.
Is MD5 technique available in other languages also example java , php?
I want my solution to be generic and not just working with .net based application only.

Login to post response

Comment using Facebook(Author doesn't get notification)