Click here to Skip to main content
15,880,651 members
Articles / Web Development / ASP.NET
Article

Tamper Proof Query String

Rate me:
Please Sign up or sign in to vote.
4.18/5 (20 votes)
22 Feb 2005CPOL3 min read 195K   1.1K   65   45
Shows how to prevent/detect that string data was changed.

Sample screenshot

Introduction

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

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

This code evaluates to something like:

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

To read the data from the query string:

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

Details

VB
'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( _
      System.Text.Encoding.UTF8.GetBytes(value)))
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))

    Try
        dataValue = System.Text.Encoding.UTF8.GetString( _
                Convert.FromBase64String(value.Split("-"c)(0)))
        storedHash = System.Text.Encoding.UTF8.GetString(_
                Convert.FromBase64String(value.Split("-"c)(1)))
        calcHash = System.Text.Encoding.UTF8.GetString( _
          mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(dataValue)))

        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.

VB
Private TamperProofKey As String = 
        ConfigurationSettings.AppSettings("TamperProofKey")
'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 
ASP.NET
<A href='yourpage.aspx?Data=<%= 
       QueryStringEncode("Your Data String") %>'>HyperLink Text</A>

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

Notes

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.

History

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

License

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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

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