Encrypt and Decrypt Query String data in ASP.NET

 

Whenever we are passing data through query string we have main security concern is whatever data we are passing through query string user can see that data and user can pass different data also.

 

To avoid this issue we have to encrypt the data before passing through query string and we have to decrypt the data once we read from query string to process further.

 

In this article we discuss about how to encrypt and decrypt the query string data. First add class, name it as EncryptDecrypt.cs and below code for that class.

 

EncryptDecrypt.cs

using System;

using System.IO;

using System.Security.Cryptography;

using System.Text;

 

namespace AspNetEncryptDecrypt

{

    public class EncryptDecrypt

    {

        private static string sCipherKey = "2013;[mCSHARP)Expert";

 

        public static string EncryptString(string sPlainText)

        {

            string EncrptKey = sCipherKey;

            byte[] byKey = { };

            byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };

            byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8));

       

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = Encoding.UTF8.GetBytes(sPlainText);

            MemoryStream ms = new MemoryStream();

            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);

            cs.FlushFinalBlock();

            return Convert.ToBase64String(ms.ToArray());

        }

 

        public static string DecryptString(string sCipherText)

        {

            sCipherText = sCipherText.Replace(" ", "+");

            string DecryptKey = sCipherKey;

            byte[] byKey = { };

            byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };

            byte[] inputByteArray = new byte[sCipherText.Length];

            byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8));

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            inputByteArray = Convert.FromBase64String(sCipherText);

            MemoryStream ms = new MemoryStream();

            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);

            cs.FlushFinalBlock();

            System.Text.Encoding encoding = System.Text.Encoding.UTF8;

            return encoding.GetString(ms.ToArray());

        }

 

        private static byte[] ReadByteArray(Stream s)

        {

            byte[] rawLength = new byte[sizeof(int)];

            if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)

            {

                throw new SystemException("Stream did not contain properly formatted byte array");

            }

 

            byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];

            if (s.Read(buffer, 0, buffer.Length) != buffer.Length)

            {

                throw new SystemException("Did not read byte array properly");

            }

            return buffer;

        }

    }

}

 

As shown above we have EncryptString and DecryptString methods. The Encryption and Decryption will happen based on cipher key(here it is sCipherKey).

 

Now use these EncryptString() and DecryptString() methods as shown below.

 

WebForm1.aspx

using System;

 

namespace AspNetEncryptDecrypt

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

 

        }

 

        protected void btn_Click(object sender, EventArgs e)

        {

            int iUserId = 100;

            Response.Redirect("WebForm2.aspx?id=" + EncryptDecrypt.EncryptString(iUserId.ToString()));

        }

    }

}


WebForm2.aspx

using System;

 

namespace AspNetEncryptDecrypt

{

    public partial class WebForm2 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            if(Request.QueryString["id"] != null)

            {

                string sUserId = EncryptDecrypt.DecryptString(Request.QueryString["id"].ToString());

                Response.Write(sUserId);

            }

        }

    }

}


As shown above we are encrypting the query string data while redirecting to WebForm2.aspx. In WebForm2.aspx we are decrypting the query string. Once we click on the button we are redirecting to WebForm2.aspx with the URL as “http://localhost:1475/WebForm2.aspx?id=z0FWLnM2zHQ=”. Here the value 100 is converted into “z0FWLnM2zHQ=”, and the encrypted value is not same every time.

                                                                                                              AspNetEncryptDecrypt.zip (26.08 kb)