Google How to Encrypt Query String in asp.net(C#, VB) | Encrypting and Decrypting Query String in asp.net(C#, VB) | Asp.Net,C#.Net,VB.Net,MVC,jQuery,JavaScipt,AJAX,WCF,Sql Server example

How to Encrypt Query String in asp.net(C#, VB) | Encrypting and Decrypting Query String in asp.net(C#, VB)

Introduction: In previous examples i explained  Encrypt and Decrypt connectionString in web.config file using code in asp.net  and How to Encrypt connection string in web.config in asp.net | How to Decrypt connection string in web.config in asp.net and Difference between DataSet and DataTable and Validate and upload image files in asp.net
Now in this article i am going to explain How to Encrypt and Decrypt Query String in asp.net

Description: As we know query string is used to pass values from one page to next page via URL so Encryption is required to prevent URL tampering and other potential security risks and also passing sensitive information e.g. password etc through Query String.

Implementation: Let's create a sample application to see the concept in action.
  • Create two pages e.g. EncryptTest.aspx and DecryptTest.aspx.
EncryptTest.aspx is the page from where you pass the value through QueryString
DecryptTest.aspx is the page from where you read the value from the QueryString
  • On EncryptTest.aspx page place a TextBox and a Button control as:
  <asp:TextBox ID="txtEmpId" runat="server"></asp:TextBox>

        <asp:Button ID="btnSubmit" runat="server" Text="Button"
            onclick="btnSubmit_Click" />

Asp.Net C# Code  to encrypt and decrypt querystring in asp.net
  • In the Code behind page(EncryptTest.aspx.cs) write code as:

First include these 3 namespaces:

using System.Security.Cryptography;
using System.IO;
using System.Text;
  • then write the code as :
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string val = Encrypt_QueryString(txtEmpId.Text.Trim());
        Response.Redirect("DecryptTest.aspx?EmpId=" + val);
    }

    public static string Encrypt_QueryString(string str)
    {
        string EncrptKey = "2013;[pnuLIT)WebCodeExpert";
        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(str);
        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());
    }
  • Now on the page DecryptTest.aspx.cs write code as:
First include these 3 namespaces:

using System.Security.Cryptography;
using System.IO;
using System.Text;
  •  then write the code as :
    protected void Page_Load(object sender, EventArgs e)
    {
        string Id = Decrypt_QueryString(Request.QueryString["EmpId"]);
        Response.Write("Emp Id =:" + Id);
    }

    public static string Decrypt_QueryString(string str)
    {
        str = str.Replace(" ", "+");
        string DecryptKey = "2013;[pnuLIT)WebCodeExpert";
        byte[] byKey = { };
        byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
        byte[] inputByteArray = new byte[str.Length];

        byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        inputByteArray = Convert.FromBase64String(str);
        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());
    }

Asp.Net VB Code to encrypt and decrypt querystring in asp.net

In the Code behind page(EncryptTest.aspx.vb) write code as:

First include these 3 namespaces:

Imports System.Text
Imports System.IO
Imports System.Security.Cryptography 
  • then write the code as :
  Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim val As String = Encrypt_QueryString(txtEmpId.Text.Trim())
        Response.Redirect("DecryptTest.aspx?EmpId=" & val)
    End Sub

    Public Shared Function Encrypt_QueryString(ByVal str As String) As String
        Dim EncrptKey As String = "2013;[pnuLIT)WebCodeExpert"
        Dim byKey As Byte() = {}
        Dim IV As Byte() = {18, 52, 86, 120, 144, 171, _
         205, 239}
        byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8))
        Dim des As New DESCryptoServiceProvider()
        Dim inputByteArray As Byte() = Encoding.UTF8.GetBytes(str)
        Dim ms As New MemoryStream()
        Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Return Convert.ToBase64String(ms.ToArray())
    End Function
  • Now on the page DecryptTest.aspx.vb write code as:
First include these 3 namespaces:

Imports System.Text
Imports System.IO
Imports System.Security.Cryptography
  • then write the code as :
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Dim Id As String = Decrypt_QueryString(Request.QueryString("EmpId"))
        Response.Write("Emp Id = :" & Id)
    End Sub

    Public Shared Function Decrypt_QueryString(ByVal str As String) As String
        str = str.Replace(" ", "+")
        Dim DecryptKey As String = "2013;[pnuLIT)WebCodeExpert"
        Dim byKey As Byte() = {}
        Dim IV As Byte() = {18, 52, 86, 120, 144, 171, _
         205, 239}
        Dim inputByteArray As Byte() = New Byte(str.Length - 1) {}

        byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8))
        Dim des As New DESCryptoServiceProvider()
        inputByteArray = Convert.FromBase64String(str)
        Dim ms As New MemoryStream()
        Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
        cs.Write(inputByteArray, 0, inputByteArray.Length)
        cs.FlushFinalBlock()
        Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
        Return encoding.GetString(ms.ToArray())
    End Function

Now over to you:
" I hope you have got the way to encrypt and decrypt the querystring and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."

13 comments :

  1. nice info

    ReplyDelete
  2. PERFECT. Exactly what I was looking for, thanks :)

    ReplyDelete
    Replies
    1. i am glad this article helped you.Stay tuned for more updates

      Delete
  3. Thanks for sharing

    ReplyDelete
  4. Just what I was looking for, thanks so much for sharing in BOTH languages.

    ReplyDelete
    Replies
    1. thanks for your valuable feedback..keep reading..

      Delete
  5. Thanx, But what if we want to generate key randomly and show different encrypted query string for same EmpID entered.

    ReplyDelete
  6. sir can you help me in my project..sir in my first page is a log in naming login.aspx.vb
    what i want to do is when you log in first time it will redirect to second page naming userchangepassword.aspx.vb and your going to change your default password,...

    Sir my problem is how to encrypt your new password and save it the database and it will redirect to the first page login.aspx.vb,...and when i input again my new password and it will decrypt,.... what i want to is in the column password the encrypted password will save i'm using sql server 2008 as my database tanks and more power...and i'm sorry about my english

    ReplyDelete
  7. sir can you help me in my project..sir in my first page is a log in naming login.aspx.vb
    what i want to do is when you log in first time it will redirect to second page naming userchangepassword.aspx.vb and your going to change your default password,...

    Sir my problem is how to encrypt your new password and save it the database and it will redirect to the first page login.aspx.vb,...and when i input again my new password and it will decrypt,.... what i want to is in the column password the encrypted password will save i'm using sql server 2008 as my database tanks and more power...and i'm sorry about my english

    ReplyDelete
  8. sir can you help me in my project..sir in my first page is a log in naming login.aspx.vb
    what i want to do is when you log in first time it will redirect to second page naming userchangepassword.aspx.vb and your going to change your default password,...

    Sir my problem is how to encrypt your new password and save it the database and it will redirect to the first page login.aspx.vb,...and when i input again my new password and it will decrypt,.... what i want to is in the column password the encrypted password will save i'm using sql server 2008 as my database tanks and more power...and i'm sorry about my english

    ReplyDelete
    Replies
    1. Hi remie mendoza..i suggest you to read the article mentioned below as per your requirement. Hope it will help you:
      How to encrypt and decrypt username,password and store in Sql Server database using asp.net C#,Vb.Net
      http://www.webcodeexpert.com/2013/08/how-to-encrypt-and-decrypt.html

      Delete
  9. Thanks a lot, your article helped me a lot

    ReplyDelete
    Replies
    1. Hi Rajesh..thanks for your feedback..it is always nice to hear that my article helped anyone..stay connected and keep reading for more useful updates..

      Delete

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..