how to encrypt query string parameters in ?


Here are some few steps do encryption of “query string” in

Step1. Create one class file in app_Code .

Step2: Keep this Code in that class

using System;
using System.Collections.Generic;
using System.IO;

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

/// <summary>
/// Summary description for QueryStringModule
/// </summary>
public class QueryStringModule : IHttpModule
//  private ILog m_Logger = LogManager.GetLogger(typeof(QueryStringModule));
#region IHttpModule Members

public void Dispose()
// Nothing to dispose

public void Init(HttpApplication context)
context.BeginRequest += new EventHandler(context_BeginRequest);


private const string PARAMETER_NAME = “enc=”;
private const string ENCRYPTION_KEY = “key”;

void context_BeginRequest(object sender, EventArgs e)
HttpContext context = HttpContext.Current;
string query = string.Empty;
string path = string.Empty;

if (context.Request.Url.OriginalString.Contains(“aspx”) && context.Request.RawUrl.Contains(“?”))
query = ExtractQuery(context.Request.RawUrl);
path = GetVirtualPath();

if (query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase))
// Decrypts the query string and rewrites the path.
string rawQuery = query.Replace(PARAMETER_NAME, string.Empty);
string decryptedQuery = Decrypt(rawQuery);
context.RewritePath(path, string.Empty, decryptedQuery);
else if (context.Request.HttpMethod == “GET”)
// Encrypt the query string and redirects to the encrypted URL.
// Remove if you don’t want all query strings to be encrypted automatically.
string encryptedQuery = Encrypt(query);
context.Response.Redirect(path + encryptedQuery, false);
catch (Exception ex)
// m_Logger.Error(“An error occurred while parsing the query string in the URL: ” + path, ex);


/// <summary>
/// Parses the current URL and extracts the virtual path without query string.
/// </summary>
/// <returns>The virtual path of the current URL.</returns>
private static string GetVirtualPath()
string path = HttpContext.Current.Request.RawUrl;
path = path.Substring(0, path.IndexOf(“?”));
path = path.Substring(path.LastIndexOf(“/”) + 1);
return path;

/// <summary>
/// Parses a URL and returns the query string.
/// </summary>
/// <param name=”url”>The URL to parse.</param>
/// <returns>The query string without the question mark.</returns>
private static string ExtractQuery(string url)
int index = url.IndexOf(“?”) + 1;
return url.Substring(index);

#region Encryption/decryption

/// <summary>
/// The salt value used to strengthen the encryption.
/// </summary>
private readonly static byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString());

/// <summary>
/// Encrypts any string using the Rijndael algorithm.
/// </summary>
/// <param name=”inputText”>The string to encrypt.</param>
/// <returns>A Base64 encrypted string.</returns>
private static string Encrypt(string inputText)
RijndaelManaged rijndaelCipher = new RijndaelManaged();
byte[] plainText = Encoding.Unicode.GetBytes(inputText);
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
using (MemoryStream memoryStream = new MemoryStream())
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
cryptoStream.Write(plainText, 0, plainText.Length);
return “?” + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray());

/// <summary>
/// Decrypts a previously encrypted string.
/// </summary>
/// <param name=”inputText”>The encrypted string to decrypt.</param>
/// <returns>A decrypted string.</returns>
private static string Decrypt(string inputText)
RijndaelManaged rijndaelCipher = new RijndaelManaged();

byte[] encryptedData = Convert.FromBase64String(inputText);
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
using (MemoryStream memoryStream = new MemoryStream(encryptedData))
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
byte[] plainText = new byte[encryptedData.Length];
int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
return Encoding.Unicode.GetString(plainText, 0, decryptedCount);



Steps 3:

Add in web config like this

<compilation debug=”true” targetFramework=”4.0″ />
<add type=”QueryStringModule ” name=”QueryStringModule “/>



Now, while passing the parameter, you will get value in encrypted form.

Like this Image

Here is no need to call that class. It is one of the easiest method to encrypt the query string.

I hope this will help to some one.


11 thoughts on “how to encrypt query string parameters in ?

  1. Best Decaptcha Service: Captcha Sniper December 14, 2012 / 9:54 pm

    Heya i am for the first time here. I came across
    this board and I find It truly useful & it helped me
    out much. I hope to give something back and help
    others like you helped me.

  2. cna test prep April 10, 2013 / 8:15 pm

    Good day! This post could not be written any better!
    Reading through this post reminds me of my old room mate!

    He always kept chatting about this. I will forward this article to him.
    Fairly certain he will have a good read. Many thanks for sharing!

  3. I blog quite often and I really appreciate your information.
    This great article has truly peaked my interest. I am
    going to take a note of your blog and keep checking for new
    information about once a week. I subscribed to your RSS feed too.

    My Web Site

    My Web Site

    My Web Site

    what is an anxiety attack like

    what is an anxiety attack like

  4. wiki mileys money method June 3, 2014 / 8:01 pm

    You really make it seem so easy with your presentation but I find this matter to
    be really something that I think I would never understand.
    It seems too complicated and very broad for me. I am looking forward for your next
    post, I will try to get the hang of it!

  5. Monique June 12, 2014 / 8:57 am

    Please let me know if you’re looking for a author for your site.
    You have some really good posts and I think I would be a good asset.
    If you ever want to take some of the load off, I’d really like
    to write some content for your blog in exchange for
    a link back to mine. Please blast me an email if interested.

  6. Going in June 12, 2014 / 11:48 am

    I get pleasure from, lead to I found just what I used
    to be taking a look for. You have ended my 4 day lengthy hunt!
    God Bless you man. Have a great day. Bye

  7. Annis June 15, 2014 / 8:32 am

    Thanks , I’ve just been looking for info about this topic for a
    long time and yours is the greatest I have came upon so far.

    However, what in regards to the conclusion? Are you positive
    about the supply?

  8. selfie stick July 15, 2014 / 11:25 am

    I relish, cause I found just what I was having a look for.

    You’ve ended my four day lengthy hunt! God Bless you man. Have a great day.

  9. Anders T October 2, 2019 / 8:33 am

    Hello Chandra Dev

    Greetings from Denmark

    I found this post while looking for something else but found i quite interesting. So I tried out the code – an easy copy/paste:
    1. The double quotes are actually not double quotes bot something else. Qutie easily fixed.
    2. But when I tested the code on a website hosted by a commercial company I got this message:
    HTTP Error 500.22 – Internal Server Error
    An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.

    Most likely causes:
    This application defines configuration in the system.web/httpModules section.

    Things you can try:
    Migrate the configuration to the system.webServer/modules section. You can do so manually or by using AppCmd from the command line – for example, %SystemRoot%\system32\inetsrv\appcmd migrate config “Default Web Site/”. Using AppCmd to migrate your application will enable it to work in Integrated mode, and continue to work in Classic mode and on previous versions of IIS.
    If you are certain that it is OK to ignore this error, it can be disabled by setting system.webServer/validation@validateIntegratedModeConfiguration to false.
    Alternatively, switch the application to a Classic mode application pool – for example, %SystemRoot%\system32\inetsrv\appcmd set app “Default Web Site/” /applicationPool:”Classic .NET AppPool”. Only do this if you are unable to migrate your application.
    (Set “Default Web Site” and “Classic .NET AppPool” to your application path and application pool name)

    Detailed Error Information:
    Module ConfigurationValidationModule
    Notification BeginRequest
    Handler ExtensionlessUrlHandler-Integrated-4.0
    Error Code 0x80070032
    Requested URL
    Physical Path d:\web\localuser\\
    Logon Method Not yet determined
    Logon User Not yet determined
    Maybe it has something to do with MS changing the validation or something but I really cannot see how I can circumvent that is the IIS is not under my control because the site i commercially hosted.

    Can you see through the problem and come up with an easy solution?

    Best regards

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.