Friday, September 6, 2013

Encrypt and Decrypt Query String in asp.net

Introduction: In this article I have explain how we can Encrypt and Decrypt Query String in asp.net.

Description:

Add a weform to project. Drag and drop the controls from Toolbox and desgin the .aspx page as given below:
<table align="center"><tr><td>Employee Name:</td><td><asp:TextBox ID="txtname" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="rfvname" runat="server"
            ControlToValidate="txtname" ErrorMessage="Enter Employee Name"
            ForeColor="#FF3300"></asp:RequiredFieldValidator>
        </td></tr>
    <tr><td>&nbsp;</td><td> <asp:Button ID="btnSubmit" runat="server" Text="Submit"
            onclick="btnSubmit_Click" /></td></tr>
    </table>    

On Button click write the below given code (.aspx.cs)
using System.Security.Cryptography;
using System.IO;
using System.Text;

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string query = EncryptQueryString(txtname.Text);
        Response.Redirect("Decrypt_QueryString.aspx?empname=" + query);
    }

    public string EncryptQueryString(string inputString)
    {
        MemoryStream memStream = null;
        try
        {
            byte[] key = { };
            byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
            string encryptKey = "aXb2uy4z";
            key = Encoding.UTF8.GetBytes(encryptKey);
            byte[] byteInput = Encoding.UTF8.GetBytes(inputString);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            memStream = new MemoryStream();
            ICryptoTransform transform = provider.CreateEncryptor(key, IV);
            CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
            cryptoStream.Write(byteInput, 0, byteInput.Length);
            cryptoStream.FlushFinalBlock();

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        return Convert.ToBase64String(memStream.ToArray());
    }

In VB (.aspx.vb)

Imports System.IO
Imports System.Text
Imports System.Security.Cryptography

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Dim query As String = EncryptQueryString(txtname.Text)
        Response.Redirect("Decrypt_QueryString.aspx?empname=" & query)
    End Sub
    Public Function EncryptQueryString(ByVal inputString As String) As String
        Dim memStream As MemoryStream = Nothing
        Try
            Dim key As Byte() = {}
            Dim IV As Byte() = {18, 52, 86, 120, 144, 171, 205, 239}
            Dim encryptKey As String = "aXb2uy4z"
            key = Encoding.UTF8.GetBytes(encryptKey)
            Dim byteInput As Byte() = Encoding.UTF8.GetBytes(inputString)
            Dim provider As New DESCryptoServiceProvider()
            memStream = New MemoryStream()
            Dim transform As ICryptoTransform = provider.CreateEncryptor(key, IV)
            Dim cryptoStream As New CryptoStream(memStream, transform, CryptoStreamMode.Write)
            cryptoStream.Write(byteInput, 0, byteInput.Length)

            cryptoStream.FlushFinalBlock()
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try
        Return Convert.ToBase64String(memStream.ToArray())
    End Function

Add a new webform to project. Here I keep its name Decrypt_QueryString.aspx, drag and drop the control from Toolbox and desgin the .aspx page as shown:
<table align="center"><tr><td>
       <asp:Label ID="lbl" runat="server" Text="Encrypted Employee Name:"
           Font-Bold="True"></asp:Label></td><td>
       <asp:Label ID="lblencry" runat="server" ForeColor="#FF3300" Font-Bold="True"
               Font-Italic="True"></asp:Label></td></tr>
   <tr><td>&nbsp;</td><td><asp:Button ID="btnSubmit" runat="server" Text="Decrypt Querystring"
            onclick="btnSubmit_Click" /></td></tr>
            <tr><td><b>
                <asp:Label ID="Label1" runat="server" Text="Decrypted Employee Name:"></asp:Label></b></td><td>
                <asp:Label ID="lbldecry" runat="server" ForeColor="#009933" Font-Bold="True"
                    Font-Italic="True"></asp:Label></td></tr>
   </table>

Write the given code on .aspx.cs page:
using System.Security.Cryptography;
using System.IO;
using System.Text;

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["empname"] != null)
        {
            lblencry.Text = (Request.QueryString["empname"]);
        }
        else
        {
            btnSubmit.Visible = false;
            lbldecry.Visible = false;
            Label1.Visible = false;
            lbl.Visible = false;
            lblencry.Text = "No Records";
        }
    }
    public string DecryptQueryString(string inputString)
    {
        MemoryStream memStream = null;
        try
        {
            byte[] key = { };
            byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
            string encryptKey = "aXb2uy4z";
            key = Encoding.UTF8.GetBytes(encryptKey);
            byte[] byteInput = new byte[inputString.Length];
            byteInput = Convert.FromBase64String(inputString);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            memStream = new MemoryStream();
            ICryptoTransform transform = provider.CreateDecryptor(key, IV);
            CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
            cryptoStream.Write(byteInput, 0, byteInput.Length);
            cryptoStream.FlushFinalBlock();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

        Encoding encoding1 = Encoding.UTF8;
        return encoding1.GetString(memStream.ToArray());
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string name= DecryptQueryString(Request.QueryString["empname"]);
       lbldecry.Text=(name);
       lblencry.Visible = false;
       lbl.Visible = false;
    }

In VB (.aspx.vb)
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Request.QueryString("empname") IsNot Nothing Then
            lblencry.Text = (Request.QueryString("empname"))
        Else
            btnSubmit.Visible = False
            lbldecry.Visible = False
            Label1.Visible = False
            lbl.Visible = False
            lblencry.Text = "No Records"
        End If
    End Sub
    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Dim nameAs String = DecryptQueryString(Request.QueryString("empname"))
        lbldecry.Text = (name)
        lblencry.Visible = False
        lbl.Visible = False
    End Sub
  
    Public Function DecryptQueryString(ByVal inputString As String) As String
        Dim memStream As MemoryStream = Nothing
        Try
            Dim key As Byte() = {}
            Dim IV As Byte() = {18, 52, 86, 120, 144, 171, 205, 239}
            Dim encryptKey As String = "aXb2uy4z"
            key = Encoding.UTF8.GetBytes(encryptKey)
            Dim byteInput As Byte() = New Byte(inputString.Length - 1) {}
            byteInput = Convert.FromBase64String(inputString)
            Dim provider As New DESCryptoServiceProvider()
            memStream = New MemoryStream()
            Dim transform As ICryptoTransform = provider.CreateDecryptor(key, IV)
            Dim cryptoStream As New CryptoStream(memStream, transform, CryptoStreamMode.Write)
            cryptoStream.Write(byteInput, 0, byteInput.Length)
            cryptoStream.FlushFinalBlock()
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try

        Dim encoding1 As Encoding = Encoding.UTF8
        Return encoding1.GetString(memStream.ToArray())
    End Function


Now run the project and check the result. If it helps you than submit your comment.

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

3 comments:

  1. There is an error in this code in Decrypt_QueryString.aspx page.
    In method public string DecryptQueryString(string inputString){}
    lines are:
    Encoding encoding1 = Encoding.UTF8;
    return encoding1.GetString(memStream.ToArray());
    while returning value it shows up an error.
    Required change is:
    Encoding encoding1 = Encoding.UTF8;
    string decrypt =" ";
    decrypt =encoding1.GetString(memStream.ToArray());
    return decrypt;

    ReplyDelete
    Replies
    1. This code was tested. There is no such problem in code. Stay in touch and keep reading.

      Delete
  2. Very nice post. I just stumbled upon your weblog and wished
    to say that I have really enjoyed browsing your blog posts.
    After all I will be subscribing to your rss feed and I hope you write again very soon!

    Here is my web-site ... business marketing

    ReplyDelete