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

Query string encryption for ASP.NET

By , 7 May 2008
 

Introduction

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.

Background

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
{
    /// <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()
        {}
    
        #endregion

        /// <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 = 
                  CryptoQueryStringHandler.DecryptQueryStrings(encryptedQueryString, 
                                                               cryptoKey);
                context.Server.Transfer(
                  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:

<httpModules>
    <add name="CryptoQueryStringUrlRemapper" 
      type="SmartSoft.QueryStringEncryption.CryptoQueryStringUrlRemapper"/>
</httpModules>

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.

History

  • 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.

License

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
Member
MCAD, MCPD Web Developer 2.0, MCPD Enterprise Developer 3.5
My company: www.helveticsolutions.com
Hopp Schwiiz Smile | :)

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
SuggestionQuery String encryption does not work when page is post back.membereli86200614 Mar '13 - 2:45 
I added a button to Default.aspx and with OnClick event I simply did Response.Write("this is test");   When i proceed further with "Send parameters as query strings" it showed me encrypted URL however, after the URL was submitted as an encrypted format I clicked newly added button and it...
GeneralRe: Query String encryption does not work when page is post back.memberFarhad Hazraty Eini24 Apr '13 - 18:58 
Hi. Use Form.Action = Request.RawUrl; at the end of page load.
Questionproblem when page postback event fire, it shows plain text in Urlmemberjitendra77719 Oct '11 - 19:52 
I tried this query string encryption but when page postback event fires it seems decryped url (param=value in plain text) in browser. please help me for above problem.
AnswerRe: problem when page postback event fire, it shows plain text in Urlmembereli86200614 Mar '13 - 2:46 
I am facing the same issue. Any resolution so far ?   Mr. Chilli.....
GeneralFor unknown reasons, the request replaces every '+' character in the query with an empty character.memberya3mro28 Jul '10 - 10:15 
for the problem you say about '+' please check the following http://stackoverflow.com/questions/3356829[^]
GeneralA code free approachmemberZiad J.khan26 Mar '10 - 0:52 
I've put all the necessary plumbing in this little library that does it all in one line of code: Session, Cookie, Query String & Cache Variables Unified [^] Hope this helps
GeneralOutput Caching not working in conjunction with query string encryption.memberjellyfish728 Sep '09 - 13:35 
This screws up output caching.   If you output cache based on a query string variable or wildcard "*", the output cache does not work due to query string encryption code calling the server.transfer and then executing code-behind again instead of outputting cache.   Server.Execute...
GeneralSerious issue with encodingmembersrouss2 Jun '09 - 23:57 
Hi   In my site I am using the exactly same process, but I fell on a big problem.   The encoded string contains '=' So of course I do UrlEncode and get ABCD%3d until there no problem. Let's say my url is www.mysite.net/SomePage.aspx?reqest=ABCD%3d   But I am using a...
GeneralThere is a major problem with this approachmemberOrionDR20 Mar '09 - 5:44 
The problem with this approach is that it still allows you to bypass the query string encryption altogether;   For instance, if I know what the query string variable you are using is, I can remove the encrypted query string and put in "?id=6" and it will bypass the decryption process...
QuestionCan still alter query string and decryption goes through and returs invalid charactorsmemberNimendra29 Sep '08 - 19:55 
Hi, Am I missing something? I altered the query string (changed one charactor, say a "A" to a "B") and investigated, the decryption goes through, and returns a string with few charactors incorrect. Any ideas? because this sort of defies the purpose, it would be great to see a solution that...

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 7 May 2008
Article Copyright 2008 by Michael Ulmann
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid