Click here to Skip to main content
15,116,525 members
Articles / Web Development / HTML
Posted 30 Apr 2008


102 bookmarked

Query string encryption for ASP.NET

Rate me:
Please Sign up or sign in to vote.
3.90/5 (29 votes)
15 Nov 2014CPOL2 min read
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 HelveticSolutions.QueryStringEncryption
    /// <summary>
    /// Http module that handles encrypted query strings.
    /// </summary>
    public class CryptoQueryStringUrlRemapper : IHttpModule
        #region IHttpModule Members

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

        public void Dispose()

        /// <summary>
        /// Event, that is called when the application acquires the request state.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        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.
  • 11th November 2014 - Namespace corrected


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 Swissworx
Australia Australia
MCAD, MCPD Web Developer 2.0, MCPD Enterprise Developer 3.5

My company: Swissworx
My blog: Sitecore Experts

Hopp Schwiiz Smile | :)

Comments and Discussions

QuestionIntegrity != Confidentiality - wrong security service Pin
Member 841817317-Nov-14 4:20
MemberMember 841817317-Nov-14 4:20 
Question"500 - Internal server error" when running it on the server Pin
fniles28-Aug-13 6:22
Memberfniles28-Aug-13 6:22 
SuggestionQuery String encryption does not work when page is post back. Pin
Elisha Cornelius14-Mar-13 3:45
MemberElisha Cornelius14-Mar-13 3:45 
GeneralRe: Query String encryption does not work when page is post back. Pin
Farhad Hazraty Eini24-Apr-13 19:58
professionalFarhad Hazraty Eini24-Apr-13 19:58 
Questionproblem when page postback event fire, it shows plain text in Url Pin
jitendra77719-Oct-11 20:52
Memberjitendra77719-Oct-11 20:52 
AnswerRe: problem when page postback event fire, it shows plain text in Url Pin
Elisha Cornelius14-Mar-13 3:46
MemberElisha Cornelius14-Mar-13 3:46 
GeneralFor unknown reasons, the request replaces every '+' character in the query with an empty character. Pin
ya3mro28-Jul-10 11:15
Memberya3mro28-Jul-10 11:15 
GeneralA code free approach Pin
Ziad J.khan26-Mar-10 1:52
professionalZiad J.khan26-Mar-10 1:52 
GeneralOutput Caching not working in conjunction with query string encryption. Pin
jellyfish728-Sep-09 14:35
Memberjellyfish728-Sep-09 14:35 
GeneralSerious issue with encoding Pin
srouss3-Jun-09 0:57
Membersrouss3-Jun-09 0:57 
GeneralThere is a major problem with this approach Pin
ErikOLeary20-Mar-09 6:44
MemberErikOLeary20-Mar-09 6:44 
QuestionCan still alter query string and decryption goes through and returs invalid charactors Pin
Nimendra29-Sep-08 20:55
MemberNimendra29-Sep-08 20:55 
GeneralAuto-Encrypting QueryStrings before Response Pin
Ruchit S.8-May-08 10:51
MemberRuchit S.8-May-08 10:51 
GeneralRe: Auto-Encrypting QueryStrings before Response Pin
cijothomas10-Jul-09 4:59
Membercijothomas10-Jul-09 4:59 
GeneralRe: Auto-Encrypting QueryStrings before Response Pin
Ruchit S.10-Jul-09 5:21
MemberRuchit S.10-Jul-09 5:21 
GeneralRe: Auto-Encrypting QueryStrings before Response Pin
thewazz17-Nov-14 9:53
professionalthewazz17-Nov-14 9:53 
GeneralSession State Pin
Allan Eagle7-May-08 5:14
MemberAllan Eagle7-May-08 5:14 
GeneralRe: Session State Pin
Michael Ulmann7-May-08 18:47
MemberMichael Ulmann7-May-08 18:47 
GeneralQuerystring decrypting on postback Pin
glacierdigital6-May-08 10:25
Memberglacierdigital6-May-08 10:25 
GeneralRe: Querystring decrypting on postback Pin
Michael Ulmann6-May-08 13:10
MemberMichael Ulmann6-May-08 13:10 
GeneralRe: Querystring decrypting on postback Pin
kraazee118-Jul-11 9:02
Memberkraazee118-Jul-11 9:02 
RantCompletely unnecessary Pin
Trumpi1-May-08 1:10
MemberTrumpi1-May-08 1:10 
GeneralRe: Completely unnecessary Pin
AndyM772-May-08 7:52
MemberAndyM772-May-08 7:52 
GeneralRe: Completely unnecessary Pin
MR_SAM_PIPER7-May-08 15:33
MemberMR_SAM_PIPER7-May-08 15:33 
GeneralRe: Completely unnecessary Pin
Michael Ulmann7-May-08 18:32
MemberMichael Ulmann7-May-08 18:32 

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

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