Click here to Skip to main content
15,310,056 members
Articles / Web Development / ASP.NET
Posted 6 Feb 2005


64 bookmarked

Tamper Proof Query String

Rate me:
Please Sign up or sign in to vote.
4.18/5 (20 votes)
22 Feb 2005CPOL3 min read
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

Comments and Discussions

GeneralMy vote of 5 Pin
zabico9-Sep-12 23:25
Memberzabico9-Sep-12 23:25 
QuestionOracle Padding Vulnerability Pin
Member 937547922-Aug-12 12:37
MemberMember 937547922-Aug-12 12:37 
Generala lil issue Pin
dlaughinjudge15-Jan-09 0:35
Memberdlaughinjudge15-Jan-09 0:35 
Generalbase64 Pin
abc22339-Jun-08 18:32
Memberabc22339-Jun-08 18:32 
General[Message Removed] Pin
Mojtaba Vali24-May-08 2:05
MemberMojtaba Vali24-May-08 2:05 
Questionhow do I use this code -- in terms of licensing? Pin
Finittz28-Apr-08 8:41
MemberFinittz28-Apr-08 8:41 
QuestionWhat is this character meants-->"-"c Pin
TerryBleMan27-Aug-07 18:16
MemberTerryBleMan27-Aug-07 18:16 
QuestionRe: What is this character meants--&gt;"-"c Pin
azote1-Jul-08 10:05
Memberazote1-Jul-08 10:05 
AnswerRe: What is this character meants--&gt;"-"c Pin
DanielHac1-Jul-08 10:09
MemberDanielHac1-Jul-08 10:09 
GeneralPassing Custom control Properties in Query String Pin
SivabalanK3-Jul-07 20:01
MemberSivabalanK3-Jul-07 20:01 
QuestionBug in QueryStringDecode Pin
PSarfas27-Apr-07 4:35
MemberPSarfas27-Apr-07 4:35 
AnswerRe: Bug in QueryStringDecode Pin
DanielHac27-Apr-07 8:31
MemberDanielHac27-Apr-07 8:31 
GeneralRe: Bug in QueryStringDecode Pin
PSarfas29-Apr-07 23:51
MemberPSarfas29-Apr-07 23:51 
AnswerRe: Bug in QueryStringDecode Pin
Vasanth Kumararajan1-Nov-07 6:25
MemberVasanth Kumararajan1-Nov-07 6:25 
GeneralRe: Bug in QueryStringDecode Pin
mz850406428-Nov-12 6:41
Membermz850406428-Nov-12 6:41 
QuestionWhat to do with the data string after decoding? Pin
metroman200212-Apr-07 9:20
Membermetroman200212-Apr-07 9:20 
QuestionDynamic Key Pin
Hunawi15-Dec-06 20:00
MemberHunawi15-Dec-06 20:00 
AnswerRe: Dynamic Key Pin
DanielHac16-Dec-06 4:30
MemberDanielHac16-Dec-06 4:30 
QuestionWhat do u do after you Decrypt?? Pin
funphxnaz10-May-06 11:06
Memberfunphxnaz10-May-06 11:06 
AnswerRe: What do u do after you Decrypt?? Pin
funphxnaz10-May-06 11:07
Memberfunphxnaz10-May-06 11:07 
GeneralRe: What do u do after you Decrypt?? Pin
funphxnaz10-May-06 12:51
Memberfunphxnaz10-May-06 12:51 
Generalinvalid base64 length Pin
Casual Jim19-Sep-05 17:38
MemberCasual Jim19-Sep-05 17:38 
GeneralRe: invalid base64 length Pin
DanielHac20-Sep-05 1:15
MemberDanielHac20-Sep-05 1:15 
GeneralRe: invalid base64 length Pin
Casual Jim20-Sep-05 11:18
MemberCasual Jim20-Sep-05 11:18 
AnswerRe: invalid base64 length Pin
Casual Jim20-Sep-05 12:31
MemberCasual Jim20-Sep-05 12: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.