Click here to Skip to main content
11,920,211 members (48,093 online)
Click here to Skip to main content
Add your own
alternative version


64 bookmarked

Tamper Proof Query String

, 22 Feb 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
Shows how to prevent/detect that string data was changed.

Sample screenshot


Have you ever wanted to allow a user to bookmark a page, but you didn't want the user to be able to manually alter the query string parameters that would be required to generate the page?

These two functions take String Data and a Key and create a protected string which, if altered will generate an error when attempting to de-protect it. It also makes it nearly impossible for the user to validate data string with out knowing the Key.

This does not encrypt the data, an experienced individual can easily decode the data. However it is encoded with "base 64 encoding" so it is not human readable. You can however encrypt data using a separate function and then pass the encrypted data to these functions to protect it from tampering.

Real world example

One possible use is to save complex SQL selection criteria. It would just confuse the user if you passed this data on the querystring and it would be very important that they couldn't alter it and send it back. This is the type of thing you might generate from an advanced search form. Passing the data on the query string allows the user to bookmark the page or save the link for future use and yet does not allow them to submit data that is not generated by your web page.

Using the code

Pass your string data and secret key to TamperProofStringEncode. This generates a protected string which can be stored in a database, file, etc.

If you want to send this data on the querystring then you also need to use HttpUtility.UrlEncode. This formats the string so that it is read properly when using Request.QueryString.

Example Usage

<A href='yourpage.aspx?Data=
<%= HttpUtility.UrlEncode(TamperProofStringEncode("Your String Data Here", 
           "Your Secret Key")) %>'>Click Here</A>

This code evaluates to something like:

<a href='yourpage.aspx?Data=
         WW91ciBTdHJpbmcgRGF0YSBIZXJl-M%2b6N4pjf280%3d'>Click Here</a>

To read the data from the query string:

  DataString = TamperProofStringDecode(Request.QueryString("Data"), _ 
          "Your Secret Key")
Catch ex As Exception
  'Invalid Data in query string
  'or data parameter not supplied
End Try


'Function to encode the string
Function TamperProofStringEncode(ByVal value As String, _
                       ByVal key As String) As String
    Dim mac3des As New System.Security.Cryptography.MACTripleDES()
    Dim md5 As New System.Security.Cryptography.MD5CryptoServiceProvider()
    mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key))
    Return Convert.ToBase64String( _
      System.Text.Encoding.UTF8.GetBytes(value)) & "-"c & _
      Convert.ToBase64String(mac3des.ComputeHash( _
End Function

'Function to decode the string
'Throws an exception if the data is corrupt
Function TamperProofStringDecode(ByVal value As String, _
          ByVal key As String) As String
    Dim dataValue As String = ""
    Dim calcHash As String = ""
    Dim storedHash As String = ""

    Dim mac3des As New System.Security.Cryptography.MACTripleDES()
    Dim md5 As New System.Security.Cryptography.MD5CryptoServiceProvider()
    mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key))

        dataValue = System.Text.Encoding.UTF8.GetString( _
        storedHash = System.Text.Encoding.UTF8.GetString(_
        calcHash = System.Text.Encoding.UTF8.GetString( _

        If storedHash <> calcHash Then
            'Data was corrupted

            Throw New ArgumentException("Hash value does not match")
            'This error is immediately caught below
        End If
    Catch ex As Exception
        Throw New ArgumentException("Invalid TamperProofString")
    End Try

    Return dataValue

End Function

Helper Functions

Optionally you can create two simple helper functions. The following are the two functions and their usage.

Private TamperProofKey As String = 
'or ... TamperProofKey As String = "YourUglyHardCodedKeyLike-alksfjlkasjfl3425"

Function QueryStringEncode(ByVal value As String) As String
  Return HttpUtility.UrlEncode(TamperProofStringEncode(value, TamperProofKey))
End Function

Function QueryStringDecode(ByVal value As String) As String
  Return TamperProofStringDecode(value, TamperProofKey)
End Function 
<A href='yourpage.aspx?Data=<%= 
       QueryStringEncode("Your Data String") %>'>HyperLink Text</A>

DataString = QueryStringDecode(Request.QueryString("Data")) 


I strongly recommend storing the key in the web.config file or at the very least in a private string variable. This prevents a typo in your code from resulting in transmitting the secret key to the client.

Please see the attached source code for more information on how to use these functions.

This function does not protect an empty string. An empty string results in the same protected value regardless of the key. Therefore if you want to allow an empty string then add a character to your data and then strip this character off when you retrieve the data. This modification could easily be added to these functions, but it makes the code more difficult to understand.

Additional Information

The ZIP file contains a working example as a single aspx page. Please try it out. The ZIP file also contains a C# class based implementation.


  • Replaced Chr(0) with "-"c to make the output string more portable. It can now be safely written to a plain text file or other basic text storage location.
  • Added a C# version class based implementation to the ZIP file.. This has currently only been tested on ASP.NET 2.0 beta 1.


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


About the Author

Web Developer
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
zabico10-Sep-12 0:25
memberzabico10-Sep-12 0:25 
QuestionOracle Padding Vulnerability Pin
Member 937547922-Aug-12 13:37
memberMember 937547922-Aug-12 13:37 
A combination of ways in which the IIS web server is setup, together with various deployment configuration and application programming issues makes it look to me as if the scenario presented within this CodeProject article is suscpetible to attack via an oracle padding issue. Do any academics care to second this (or even care to elaborate?)   Shucks | :-\    I could be wrong since my conclusion was drawn from an observation made at a glance. However, I'd like to estimate my capability of recognizing such subtle issues.

Regards code projectors,  

Derek Callaway
Digital Security Consultant

P.S. Thanks in advance, if/when any responses show up..
Generala lil issue Pin
dlaughinjudge-nonso15-Jan-09 1:35
memberdlaughinjudge-nonso15-Jan-09 1:35 
Generalbase64 Pin
abc22339-Jun-08 19:32
memberabc22339-Jun-08 19:32 
General[Message Removed] Pin
Mojtaba Vali24-May-08 3:05
memberMojtaba Vali24-May-08 3:05 
Questionhow do I use this code -- in terms of licensing? Pin
Finittz28-Apr-08 9:41
memberFinittz28-Apr-08 9:41 
QuestionWhat is this character meants-->"-"c Pin
Nick Meng27-Aug-07 19:16
memberNick Meng27-Aug-07 19:16 
QuestionRe: What is this character meants--&gt;"-"c Pin
azote1-Jul-08 11:05
memberazote1-Jul-08 11:05 
AnswerRe: What is this character meants--&gt;"-"c Pin
DanielHac1-Jul-08 11:09
memberDanielHac1-Jul-08 11:09 
GeneralPassing Custom control Properties in Query String Pin
sivabalank3-Jul-07 21:01
membersivabalank3-Jul-07 21:01 
QuestionBug in QueryStringDecode Pin
PSarfas27-Apr-07 5:35
memberPSarfas27-Apr-07 5:35 
AnswerRe: Bug in QueryStringDecode Pin
DanielHac27-Apr-07 9:31
memberDanielHac27-Apr-07 9:31 
GeneralRe: Bug in QueryStringDecode Pin
PSarfas30-Apr-07 0:51
memberPSarfas30-Apr-07 0:51 
AnswerRe: Bug in QueryStringDecode Pin
Vasantha Mohan1-Nov-07 7:25
memberVasantha Mohan1-Nov-07 7:25 
GeneralRe: Bug in QueryStringDecode Pin
Member 850406428-Nov-12 7:41
memberMember 850406428-Nov-12 7:41 
QuestionWhat to do with the data string after decoding? Pin
metroman200212-Apr-07 10:20
membermetroman200212-Apr-07 10:20 
QuestionDynamic Key Pin
Hunawi15-Dec-06 21:00
memberHunawi15-Dec-06 21:00 
AnswerRe: Dynamic Key Pin
DanielHac16-Dec-06 5:30
memberDanielHac16-Dec-06 5:30 
QuestionWhat do u do after you Decrypt?? Pin
funphxnaz10-May-06 12:06
memberfunphxnaz10-May-06 12:06 
AnswerRe: What do u do after you Decrypt?? Pin
funphxnaz10-May-06 12:07
memberfunphxnaz10-May-06 12:07 
GeneralRe: What do u do after you Decrypt?? Pin
funphxnaz10-May-06 13:51
memberfunphxnaz10-May-06 13:51 
Generalinvalid base64 length Pin
Casual Jim19-Sep-05 18:38
memberCasual Jim19-Sep-05 18:38 
GeneralRe: invalid base64 length Pin
DanielHac20-Sep-05 2:15
sussDanielHac20-Sep-05 2:15 
GeneralRe: invalid base64 length Pin
Casual Jim20-Sep-05 12:18
memberCasual Jim20-Sep-05 12:18 
AnswerRe: invalid base64 length Pin
Casual Jim20-Sep-05 13:31
memberCasual Jim20-Sep-05 13:31 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151120.1 | Last Updated 22 Feb 2005
Article Copyright 2005 by DanielHac
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid