How to encrypt query string in ASP.NET.




Introduction

In this post I am explain how to encrypt query string in ASP.NET
We know that ASP.NET Web application is State less because HTTP is State less. So, If you want your application redirects from one ASP.NET Web page to another, you will not get any information from your previous page. To overcome this there are some technique in asp.net to pass information form one page to another and most popular of them is Query String.

But if we pass information in query string and our information is related to out database id then for security reasons, we should not pass direct and clear information in your URL query strings. So we need to hide this information by encrypting the URL query strings.

We can do this by following this below steps. Here I create a project, that show list of products with link to show product details. Here pass product id (encrypted) as query string.

Steps :

Just follow the steps and get result easily.

Step-1 : Create New Project

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table and insert data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add a Class for encryption / decrypt Query string.

Go to Solution Explorer > Right Click on Project under solution explorer > Add > New item > Select Class under Code > Enter Name > Add.

public static class MyCrypto
    {
        private static string Key = "ABC123DEF456GH78";
        private static byte[] GetByte(string data)
        {
            return Encoding.UTF8.GetBytes(data);
        }

        public static byte[] EncryptString(string data)
        {
            byte[] byteData = GetByte(data);
            SymmetricAlgorithm algo = SymmetricAlgorithm.Create();
            algo.Key = GetByte(Key);
            algo.GenerateIV();

            MemoryStream mStream = new MemoryStream();
            mStream.Write(algo.IV, 0, algo.IV.Length);

            CryptoStream myCrypto = new CryptoStream(mStream, algo.CreateEncryptor(), CryptoStreamMode.Write);
            myCrypto.Write(byteData, 0, byteData.Length);
            myCrypto.FlushFinalBlock();

            return mStream.ToArray();
        }

        public static string DecryptString(byte[] data)
        {
            SymmetricAlgorithm algo = SymmetricAlgorithm.Create();
            algo.Key = GetByte(Key);
            MemoryStream mStream = new MemoryStream();

            byte[] byteData = new byte[algo.IV.Length];
            Array.Copy(data, byteData, byteData.Length);
            algo.IV = byteData;
            int readFrom = 0;
            readFrom += algo.IV.Length;

            CryptoStream myCrypto = new CryptoStream(mStream, algo.CreateDecryptor(), CryptoStreamMode.Write);
            myCrypto.Write(data, readFrom, data.Length - readFrom);
            myCrypto.FlushFinalBlock();

            return Encoding.UTF8.GetString(mStream.ToArray());
        }

        public static string GetEncryptedQueryString(string data)
        {
            return Convert.ToBase64String(EncryptString(data));
        }

        public static string GetDecryptedQueryString(string data)
        {
            byte[] byteData = Convert.FromBase64String(data.Replace(" ","+"));
            return DecryptString(byteData);
        }

    }

Step-6: Create page for show list of product.

Go to Solution Explorer > Right Click on Project under solution explorer > Add > New item > Select Web Form under Web > Enter Name > Add.


Gridview Design

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
                CellPadding="10" CellSpacing="1" BackColor="Black"
                RowStyle-BackColor="White"
                HeaderStyle-BackColor="White">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <div><img src='ProductImage/<%#Eval("ImagePath")%>' width="50px" border="0"/></div>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderText="Product" DataField="ProductName" />
                <asp:BoundField HeaderText="Price" DataField="Price" />           
                <asp:BoundField HeaderText="Category" DataField="Category" />
                <asp:TemplateField>
                    <ItemTemplate>
                       <a href='ProductDetails.aspx?id=<%#ASPQueryStringEncryption.MyCrypto.GetEncryptedQueryString(Eval("ProductID").ToString()) %>'>View Details</a>
                    </ItemTemplate>
                </asp:TemplateField>               
            </Columns>

        </asp:GridView>

Here <%#ASPQueryStringEncryption.MyCrypto.GetEncryptedQueryString(Eval("ProductID").ToString()) %> is for Encrypt Query String (product ID)

Write the followings code in your page load event for fetch Data from Database.

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                populateData();
            }
        }

        private void populateData()
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var v = dc.ProductMasters.ToList();
                GridView1.DataSource = v;
                GridView1.DataBind();
            }

        }



Step-7: Create page for show product details.

Go to Solution Explorer > Right Click on Project under solution explorer > Add > New item > Select Web Form under Web > Enter Name > Add.

Design for Product Details


<h2>Product Details</h2>
    <table border="0" cellpadding="0" cellspacing="5">
        <tr>
            <td rowspan="6">
                <asp:Image ID="Image1" runat="server" Width="120px"  />
            </td>
            <td>Product Name :</td>
            <td>
                <asp:Label ID="lblProductName" runat="server" />
            </td>
        </tr>
        <tr>
            <td>Price : </td>
            <td>
                <asp:Label ID="lblPrice" runat="server" />
            </td>
        </tr>
        <tr>
            <td>Available Colors :</td>
            <td>
                <asp:Label ID="lblAvailableColors" runat="server" />
            </td>
        </tr>
        <tr>
            <td>Brand :</td>
            <td>
                <asp:Label ID="lblBrand" runat="server" />
            </td>
        </tr>
        <tr>
            <td>Category :</td>
            <td>
                <asp:Label ID="lblCategory" runat="server" />
            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <asp:Button ID="btnAddToCart" runat="server" Text="Add to cart" />
            </td>
        </tr>

    </table>


Write the followings code in your page load event for fetch Data from Database.

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int id = 0;
                if (Request.QueryString["id"] != null)
                {
                    if (int.TryParse(MyCrypto.GetDecryptedQueryString(Request.QueryString["id"].ToString()),out id))
                    {
                        populateData(id);
                    }
                }
            }
        }

        private void populateData(int id)
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var v = dc.ProductMasters.Where(a => a.ProductID.Equals(id)).FirstOrDefault();
                if (v != null)
                {
                    Image1.ImageUrl = "ProductImage/" + v.ImagePath;
                    lblProductName.Text = v.ProductName;
                    lblPrice.Text = v.Price.ToString();
                    lblBrand.Text = v.Brand;
                    lblAvailableColors.Text = v.AvailableColors;
                    lblCategory.Text = v.Category;
                }
            }

        }

Here MyCrypto.GetDecryptedQueryString(Request.QueryString["id"].ToString() is for decrypt Query String (product id).

Step-8: Run Application.


Related Post:

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.