May 28, 2013

Encrypt and Decrypt Query String

On web, there are a lot of encryption decryption methods are available, you can choose any of them.

Redirecting from one page to another page using query string is done by every developer around the world but best approach is to encode your query parameter and decode it in next page. 

But here I'm using simple way of encoding and decoding using ASCII encode decode class. So, let's get down to the code here is basic encryption.

-------------------------------
ASPX CODE  (PAGE 1) :
-------------------------------

<div>
    <p>
        <asp:TextBox ID="InputText" runat="server" />
    </p>
    <p>
        <asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
    </p>
</div>
------------------------------------------
ASPX CODE-BEHIND  (PAGE 1) :
------------------------------------------

protected void SubmitButton_Click(object sender, EventArgs e)
{
    string inputText = InputText.Text.Trim();

    if (inputText != "")
    {
        string encodeString = 
            Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(inputText));
        Response.Redirect("Page2.aspx?search=" + encodeString);
    }
}
------------------------------------------
ASPX CODE-BEHIND  (PAGE 2) :
------------------------------------------

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string decodeString =
            ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(Request.QueryString["search"]));

        if (decodeString == "1")
        {
            Response.Write("Hello World");
        }
        else 
        {
            Response.Write(decodeString);
        }
    }
}

Output will be as:



Cheers

No comments:

Post a Comment