Home > ASP.Net > Encrypt and Decrypt QueryString in Gridview

Encrypt and Decrypt QueryString in Gridview


Hi all,

try this example to Encrypt and Decrypt QueryString in Gridview

In this example i will use Northwind Database (Categories and Products tables)

1) Open VS2008 and create new web site

2) Add Web.Config and add the connection string to database


<connectionStrings>
 <add name="NorthwindConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>

3) Add new Class name it “Encriptor.cs” and add the following code which will Encrypt and Decrypt Querystring :-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using System.Text;

/// <summary>
/// Summary description for Encriptor
/// </summary>
public class Encriptor
{
 public Encriptor()
 {
 }

const string DESKey = "AQWSEDRF";
 public static int key = 129;

public static string Encrypt(string strToEncrypt, string strKey)
 {
 try
 {
 TripleDESCryptoServiceProvider objDESCrypto =
 new TripleDESCryptoServiceProvider();
 MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
 byte[] byteHash, byteBuff;
 string strTempKey = strKey;
 byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
 objHashMD5 = null;
 objDESCrypto.Key = byteHash;
 objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
 byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
 return Convert.ToBase64String(objDESCrypto.CreateEncryptor().
 TransformFinalBlock(byteBuff, 0, byteBuff.Length));
 }
 catch (Exception ex)
 {
 return "Wrong Input. " + ex.Message;
 }
 }

/// <summary>
 /// Decrypt the given string using the specified key.
 /// </summary>
 /// <param name="strEncrypted">The string to be decrypted.</param>
 /// <param name="strKey">The decryption key.</param>
 /// <returns>The decrypted string.</returns>
 public static string Decrypt(string strEncrypted, string strKey)
 {
 try
 {
 TripleDESCryptoServiceProvider objDESCrypto =
 new TripleDESCryptoServiceProvider();
 MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
 byte[] byteHash, byteBuff;
 string strTempKey = strKey;
 byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
 objHashMD5 = null;
 objDESCrypto.Key = byteHash;
 objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
 byteBuff = Convert.FromBase64String(strEncrypted);
 string strDecrypted = ASCIIEncoding.ASCII.GetString
 (objDESCrypto.CreateDecryptor().TransformFinalBlock
 (byteBuff, 0, byteBuff.Length));
 objDESCrypto = null;
 return strDecrypted;
 }
 catch (Exception ex)
 {
 return "Wrong Input. " + ex.Message;
 }
 }

public static string decryptQueryString(string stringToDecrypt)//Decrypt the content
 {
 byte[] c = Convert.FromBase64String(stringToDecrypt);
 string decryptedConnectionString = System.Text.UTF32Encoding.UTF32.GetString(c);
 decryptedConnectionString = decryptedConnectionString.Replace("_V_", " ");
 return decryptedConnectionString;
 return stringToDecrypt;
 return Decrypt(stringToDecrypt, DESKey);
 }

public static string Reverse(string str)
 {
 int len = str.Length;
 char[] arr = new char[len];
 for (int i = 0; i < len; i++)
 {
 arr[i] = str[len - 1 - i];
 }
 return new string(arr);
 }

public static string ReverseAdvanced(string str, bool isenc)
 {
 string result = Reverse(str);
 if (!(str.Length < 3))
 {
 for (int i = 0; i < str.Length; i++)
 {
 ShiftMiddle(result, isenc);
 }
 }
 return result;
 }
 public static string encryptQueryString(string stringToEncrypt)// Encrypt the content
 {
 stringToEncrypt = stringToEncrypt.Replace(" ", "_V_");
 byte[] b = System.Text.UTF32Encoding.UTF32.GetBytes(stringToEncrypt);
 string encryptedConnectionString = Convert.ToBase64String(b);
 return encryptedConnectionString;
 return stringToEncrypt;
 return Encrypt(stringToEncrypt, DESKey);
 return stringToEncrypt + "x";
 }

static byte[] Convert2ByteArray(string strInput)
 {
 int intCounter; char[] arrChar;
 arrChar = strInput.ToCharArray();
 byte[] arrByte = new byte[arrChar.Length];

for (intCounter = 0; intCounter <= arrByte.Length - 1; intCounter++)
 arrByte[intCounter] = Convert.ToByte(arrChar[intCounter]);
 return arrByte;
 }
}

4) Add new Web Page and from Toolbox drag Gridview control


<div>
 <asp:GridView ID="GV_Category" runat="server" AutoGenerateColumns="False"
 DataKeyNames="CategoryID" CellPadding="4" ForeColor="#333333">
 <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
 <Columns>
 <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" ReadOnly="true" InsertVisible="False"
 SortExpression="CategoryID" />
 <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
 <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
 <asp:TemplateField>
 <ItemTemplate>
 <a href="#" onclick="window.open('Product_Detail.aspx?CategoryID=<%# Encriptor.encryptQueryString(DataBinder.Eval(Container.DataItem,"CategoryID").ToString())%>'); return false">Products Detail</a>
 </ItemTemplate>
 </asp:TemplateField>
 </Columns>
 <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
 <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
 <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
 <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
 <AlternatingRowStyle BackColor="White" />
 </asp:GridView>
 </div>

5)  Now we want to bind that Gridview to Categories table so in code behind we will add the following code :-


protected void Page_Load(object sender, EventArgs e)
 {
 if (!IsPostBack)
 {
 SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
 SqlCommand comm = new SqlCommand("Select * from Categories", conn);
 DataSet ds = new DataSet();
 SqlDataAdapter adpter = new SqlDataAdapter(comm);
 adpter.Fill(ds);
 GV_Category.DataSource = ds;
 GV_Category.DataBind();
 }
 }

Don’t forget to use the following Namespace

using System.Data.SqlClient;

6) Add Another Web Page called “Product_Detail.aspx” and from Toolbox drag Gridview control to bind Products for each Category using Querystring


<div>
 <asp:GridView ID="gvProducts" runat="server"
 CssClass="datagrid" AutoGenerateColumns="False"
 DataKeyNames="ProductID" CellPadding="4" ForeColor="#333333">
 <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
 <Columns>
 <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="true"
 InsertVisible="False" SortExpression="ProductID" />
 <asp:BoundField DataField="ProductName" HeaderText="ProductName"
 SortExpression="ProductName" />
 <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit"
 SortExpression="QuantityPerUnit" />
 <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"
 SortExpression="UnitPrice" />
 </Columns>
 <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
 <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
 <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
 <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
 <AlternatingRowStyle BackColor="White" />
 </asp:GridView>
 </div>

7) In Code behind we will add the following Code :-


protected void Page_Load(object sender, EventArgs e)
 {
 if (!IsPostBack)
 {
 SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
 SqlCommand comm = new SqlCommand("Select * from Products where CategoryID = @CategoryID", conn);
 comm.Parameters.Add("@CategoryID", SqlDbType.Int).Value = Encriptor.decryptQueryString(Request.QueryString["CategoryID"]);
 DataSet ds = new DataSet();
 SqlDataAdapter adpter = new SqlDataAdapter(comm);
 adpter.Fill(ds);
 gvProducts.DataSource = ds;
 gvProducts.DataBind();
 }
 }

Hope this helps

Good Luck

Advertisements
Categories: ASP.Net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: