Click here to Skip to main content
Click here to Skip to main content

Query string encryption for ASP.NET

, 7 May 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
Clear text query strings are a potential security threat for your web application. Thus, query strings should always be encrypted.


Using query strings to send data from the browser to the server is a widespread approach. Giving the visitor of a web application the opportunity of modifying query strings by transmitting them in clear text, is certainly a potential security threat.

Thus, I encourage developers to encrypt query strings, even if they do not contain confidential data. However, I am aware that it is still possible to alternate an encrypted query string, but with an appropriate exception handling, this is harmless.


To keep this article simple, I used a contradictable encryption (DES encoding), though any cutting-edge encryption can be easily applied to the samples given.

Using the code

So, let's get down to business. The main part of the presented solution consists of a HttpModule which decrypts the query string and hence provides the page request with the ordinary unencrypted query strings:

using System;
using System.Web;
using System.Web.Configuration;

namespace SmartSoft.QueryStringEncryption
    /// <span class="code-SummaryComment"><summary></span>
    /// Http module that handles encrypted query strings.
    /// <span class="code-SummaryComment"></summary></span>
    public class CryptoQueryStringUrlRemapper : IHttpModule
        #region IHttpModule Members

        /// <span class="code-SummaryComment"><summary></span>
        /// Initialize the http module.
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="application">Application,</span>
        ///           that called this module.<span class="code-SummaryComment"></param></span>
        public void Init(HttpApplication application)
            // Attach the acquire request state event
            // to catch the encrypted query string
            application.AcquireRequestState += application_AcquireRequestState;

        public void Dispose()

        /// <span class="code-SummaryComment"><summary></span>
        /// Event, that is called when the application acquires the request state.
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="sender"></param></span>
        /// <span class="code-SummaryComment"><param name="e"></param></span>
        public void application_AcquireRequestState(object sender, EventArgs e)
            // Get http context from the caller.
            HttpApplication application = (HttpApplication) sender;
            HttpContext context = application.Context;

            // Check for encrypted query string
            string encryptedQueryString = context.Request.QueryString["request"];
            if (!string.IsNullOrEmpty(encryptedQueryString))
                // Decrypt query strings
                string cryptoKey = WebConfigurationManager.AppSettings["CryptoKey"];
                string decryptedQueryString = 
                  context.Request.AppRelativeCurrentExecutionFilePath + 
                  "?" + decryptedQueryString);

As you might have noticed, if there is an encrypted query string for the current request, the module automatically terminates the execution of the current page and internally starts execution of a new request on the server.

The next step is to register the HttpModule in the web.config file:

    <add name="CryptoQueryStringUrlRemapper" 

Last but not least, do not forget to encrypt query strings before sending them back to the server:

private void PrepareSendButton()
    NameValueCollection queryStrings = new NameValueCollection();
    queryStrings.Add("param1", "Test1");
    queryStrings.Add("param2", "Test2");
    queryStrings.Add("param3", "Test3");

    // Encrypt query strings
    string encryptedString = CryptoQueryStringHandler.EncryptQueryStrings(
      queryStrings, WebConfigurationManager.AppSettings["CryptoKey"]);
    btnSendParams.PostBackUrl = string.Concat("~/Default.aspx?", encryptedString);

As outlined earlier in this article, the encryption class can be easily replaced by any other encryption class. A full running sample can be downloaded above.

Important issue

The method DecryptQueryStrings in the CryptoQueryStringHandler contains the following line :

return Encryption64.Decrypt(encryptedStrings.Replace(" ", "+"), key); 

For unknown reasons, the request replaces every '+' character in the query with an empty character.


  • 30.04.2008 - First version (deleted -> was not possible to modify, why ever...).
  • 01.05.2008 - Re-released updated article.
  • 08.05.2008 - BeginRequest event in the HttpModule changed to AcquireRequestState in order to support Session data.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Michael Ulmann
Architect Helvetic Solutions
Australia Australia
MCAD, MCPD Web Developer 2.0, MCPD Enterprise Developer 3.5
My company:
Hopp Schwiiz Smile | :)

Comments and Discussions

Question"500 - Internal server error" when running it on the server Pinmemberfniles28-Aug-13 5:22 
SuggestionQuery String encryption does not work when page is post back. Pinmembereli86200614-Mar-13 2:45 
GeneralRe: Query String encryption does not work when page is post back. PinmemberFarhad Hazraty Eini24-Apr-13 18:58 
Questionproblem when page postback event fire, it shows plain text in Url Pinmemberjitendra77719-Oct-11 19:52 
AnswerRe: problem when page postback event fire, it shows plain text in Url Pinmembereli86200614-Mar-13 2:46 
GeneralFor unknown reasons, the request replaces every '+' character in the query with an empty character. Pinmemberya3mro28-Jul-10 10:15 
GeneralA code free approach PinmemberZiad J.khan26-Mar-10 0:52 
GeneralOutput Caching not working in conjunction with query string encryption. Pinmemberjellyfish728-Sep-09 13:35 
GeneralSerious issue with encoding Pinmembersrouss2-Jun-09 23:57 
GeneralThere is a major problem with this approach PinmemberOrionDR20-Mar-09 5:44 
QuestionCan still alter query string and decryption goes through and returs invalid charactors PinmemberNimendra29-Sep-08 19:55 
GeneralAuto-Encrypting QueryStrings before Response PinmemberRuchit Surati8-May-08 9:51 
GeneralRe: Auto-Encrypting QueryStrings before Response Pinmembercijothomas10-Jul-09 3:59 
GeneralRe: Auto-Encrypting QueryStrings before Response PinmemberRuchit S.10-Jul-09 4:21 
GeneralSession State PinmemberAllan Eagle7-May-08 4:14 
GeneralRe: Session State PinmemberMichael Ulmann7-May-08 17:47 
GeneralQuerystring decrypting on postback PinmemberLordGentle6-May-08 9:25 
GeneralRe: Querystring decrypting on postback PinmemberMichael Ulmann6-May-08 12:10 
GeneralRe: Querystring decrypting on postback Pinmemberkraazee118-Jul-11 8:02 
RantCompletely unnecessary PinmemberTrumpi1-May-08 0:10 
GeneralRe: Completely unnecessary PinmemberAndyM772-May-08 6:52 
GeneralRe: Completely unnecessary PinmemberMR_SAM_PIPER7-May-08 14:33 
GeneralRe: Completely unnecessary PinmemberMichael Ulmann7-May-08 17:32 
GeneralRe: Completely unnecessary PinmemberMatt Sollars13-May-08 3:18 
POST over HTTPS only hides the data during transit. Once the data is received by the requesting user, he/she need only view the source of the page to see things. True, it would take a little more effort to change and re-post the data, but with browser add-ons nowadays, it's not too difficult.
Let's not forget the concept of bookmarking pages that have such parameters too. Data sent via POST over HTTPS cannot be bookmarked. An encrypted query string is quite "bookmarkable". Thus, the idea of this solution doesn't seem unnecessary to me at all.


(Find your own niche! This one's mine.)

GeneralRe: Completely unnecessary Pinmemberwk63313-May-08 4:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141022.2 | Last Updated 7 May 2008
Article Copyright 2008 by Michael Ulmann
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid