Monday, June 24, 2013

How to Encrypt and Decrypt Query String in ASP.NET?

Query string is a common and popular way to pass values between pages but it is not a safer way because all the values are visible to users in normal text format. Users can change and play with these values so there is security issue involved with query string way of passing values to between pages.  You can use other techniques to pass values between pages but there may be some situations when you need to pass some values using query string and you don’t want to show these values to users.  Encrypt query string is the way to handle this situation. You can encrypt your query string values and pass these values in URL. Later you can decrypt these values to see in normal text.

  1. Create new website in Visual Studio 2010
  2. Add a Default.aspx web form in the website
  3. Add another web form and rename the page as Page2.aspx
  4. Add a button in Default.aspx page

    <asp:Button ID="btnEncrypt" runat="server"
           Text="Go to Page 2 with encrypted query string " onclick="btnEncrypt_Click" />
     
  5. Add a button and a label in Page2.aspx

    <asp:Button ID="btnDerypt" runat="server"
          Text="Click to see decrypted query string" onclick="btnDecrypt_Click" />
    <br />
    <asp:Label ID="lblURL" runat="server" ></asp:Label>
     
  6. We have to use following namespaces in our code

    C#
     
    using System.IO;
    using System.Text;
    using System.Security.Cryptography;
     
    VB.NET

    Imports System.IO
    Imports System.Text
    Imports System.Security.Cryptography
     
  7. Add a function in code file of Default.aspx for encryption

    C#

    public string EncryptString(string inputString)
    {
        MemoryStream memStream = null;
        try
        {
            byte[] key = { };
            byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };
            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());
    }
     
    VB.NET

    Public Function EncryptString(ByVal inputString As String) As String
        Dim memStream As MemoryStream = Nothing
        Try
            Dim key As Byte() = {}
            Dim IV As Byte() = {12, 21, 43, 17, 57, 35, 67, 27}
            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
     
    Create two byte arrays for key and IV and set your key and IV. Call the GetBytes method to get the string as bytes. Create an instance of DESCryptoServiceProvider class. Create an instance of ICryptoTransform class and call the CreateEncryptor() method by providing secret Key and IV. Create instance of CryptoStream class by providing byte input, offset and length.  Call the FlushFinalBlock() method of CryptoStream class to update the currently buffered data to MemoryStream. At the end, return the Memory stream array by converting it to Base64 string.
     
  8. Add a button click event in code file of Default.aspx page to redirect to Page2.aspx

    C#
     
    protected void btnEncrypt_Click(object sender, EventArgs e)
    {
        string url = "Page2.aspx?";
        string queryString = "id=10&name=wayne";
        string encryptedQueryString = EncryptString(queryString);
        string urlWithEncryptedString = url + encryptedQueryString;
        Response.Redirect(urlWithEncryptedString);
    }
     
    VB.NET
     
    Protected Sub btnEncrypt_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnEncrypt.Click
        Dim url As String = "Page2.aspx?"
        Dim queryString As String = "id=10&name=wayne"
        Dim encryptedQueryString As String = EncryptString(queryString)
        Dim urlWithEncryptedString As String = url & encryptedQueryString
        Response.Redirect(urlWithEncryptedString)
    End Sub
     
    Call the EncryptString() method by providing query string and redirect the page to Page2.aspx.
     
  9. Add a function in code file of Page2.aspx for decryption
     
    C#
     
    public string DecryptString(string inputString)
    {
        MemoryStream memStream = null;
        try
        {
            byte[] key = { };
            byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };
            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());
    }
     
    VB.NET
     
    Public Function DecryptString(ByVal inputString As String) As String
        Dim memStream As MemoryStream = Nothing
        Try
            Dim key As Byte() = {}
            Dim IV As Byte() = {12, 21, 43, 17, 57, 35, 67, 27}
            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
     
    Decrypt query string by using same key and IV.  Convert the string from Base64 to byte array. Call the CreateDecryptor() method here by passing same key and IV. Create instance of CryptoStream class by providing byte input, offset and length.  Call the FlushFinalBlock() method of CryptoStream class to update the currently buffered data to MemoryStream. At the end, call GetString() method to get data from memory stream array.
     
  10. Add a button click event in code file of Page2.aspx to display the decrypted query string

    C#
     
    protected void btnDecrypt_Click(object sender, EventArgs e)
    {
        string url = Request.RawUrl;
        string urlEnrypted = url.Substring(url.IndexOf('?') + 1);
        string decryptedUrl = DecryptString(urlEnrypted);
        lblURL.Text = decryptedUrl;
    }
     
    VB.NET

    Protected Sub btnDecrypt_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDerypt.Click
        Dim url As String = Request.RawUrl
        Dim urlEnrypted As String = url.Substring(url.IndexOf("?") + 1)
        Dim decryptedUrl As String = DecryptString(urlEnrypted)
        lblURL.Text = decryptedUrl
    End Sub
     
    Get the raw URL of the current page and get the encrypted part of the URL which is query string parameters after question mark (?).
     
  11. Set Default.aspx page as Start Page and start debugging.  


No comments:

Post a Comment