Query String Encrypt Decrypt in asp .net

In this asp .net tutorial we will learn how to encrypt and decrypt query string for security purposes. Encryption and Decryption of query string is very necessary as query strings are exposed to users and users can alter values of query strings. In this article we will use inbuilt Encrypt and Decrypt methods available in asp .net 4.0 and asp .net 4.5 to Encrypt and Decrypt our query string.
 

For more information about how to Encrypt Decrypt in Asp .Net you can follow this article: 

Encrypt Decrypt text in asp .net 4.5, 4.0 and lower versions
 

Step1 Make a new asp .net website.

Step2: Add new webpage to your website. Add add two button in it.

 

 
 

 


Using Asp .Net 4.0

 

 protected void btn40_Click(object sender, EventArgs e)
    {
        var plaintextBytes = Encoding.UTF8.GetBytes("Hello");
        var encryptedValue = MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);
        Response.Redirect("Default2.aspx?name=" + encryptedValue);
    }

 


Using Asp .Net 4.5 

 

 protected void btn45_Click(object sender, EventArgs e)
    {
        var plaintextBytes = Encoding.UTF8.GetBytes("Max");

        //---- Encrypt text.
        var encryptedValue = Convert.ToBase64String(MachineKey.Protect(plaintextBytes, "Anuj"));

        //--- URL encode to make encrypted value URL compatible.
        encryptedValue = HttpUtility.UrlEncode(encryptedValue);

        //---- Send encrypted value as query string.
        Response.Redirect("Default3.aspx?name=" + encryptedValue);
    }

 

 

Add following NameSpaces in Default2.aspx.cs and in Default3.aspx.cs pages.

 

using System.Text;
using System.Web.Security;

 


Add a new Default2.aspx page in your website.

 

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString.ToString()))
        {
            var decryptedBytes = MachineKey.Decode(Request.QueryString["name"], MachineKeyProtection.All);
            var decryptedValue = Encoding.UTF8.GetString(decryptedBytes);
            Response.Write(decryptedValue);
        }
    }

 

 

Add a new Default3.aspx page in your website.

 

 

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString.ToString()))
        {
            var bytes = Convert.FromBase64String(Request.QueryString["name"].ToString());
            var output = MachineKey.Unprotect(bytes, "Anuj");
            Response.Write(Encoding.UTF8.GetString(output));
        }
    }

 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice