HttpModule for query string encryption

by Mads Kristensen 25. January 2007 04:40

URL parameters or query strings are often used to carry information that can be used by hackers to do identity theft or other unpleasant things. Consider the URL example.com/?user=123&account=456 and then imaging what a hacker could do with it. Security or not, sometimes you just don’t want the visitors to see all the query strings for whatever reason.

In those cases it would be nice if we could encrypt the entire query string so it wouldn’t carry any readable information. The problem with one big encrypted query string is that we would break all the code that referenced the query. Code like Request.QueryString["user"] would no longer work, but as usual ASP.NET has the answer to that problem.

What we need is an HttpModule that can turn the encrypted query string into a normal readable one, so that we can still use our old logic like Request.QueryString["user"]. In other words, we want the user to see this

?enc=VXzal017xHwKKPolDWQJoLACDqQ0fE//wGkgvRTdG/GgXIBDd1

while your code sees this

?user=123&account=456.

The HttpModule

The module we need for this task must be able to do a few simple things. It must be able to encrypt the regular query string so that all your current links will automatically be encrypted. It must also be able to decrypt it again so that you can write the code as you normally would. It must also provide a method for encrypting a regular query string if you don’t want to use automatic encryption.

The most important feature of the module is to make it totally plug ‘n play. You should be able to apply the module to any existing website and automatically have query string encryption and decryption without changing any of your code.

Implementation

Download the QueryStringModule.cs below and put it in the App_Code folder of your website. Then add the following lines to the web.config’s <system.web> section:

< httpModules >

  < add type = " QueryStringModule " name = " QueryStringModule " />

</ httpModules >

Because automatic encryption is not always desirable the module has a comment that tells you how to turn it off. The module is well commented and should be easy to modify for any ASP.NET developer.

Example

You can encrypt query strings by using the Encrypt() method of the module from any web page or user control.

string query = QueryStringModule .Encrypt( "user=123&account=456" );

Then just add the encrypted query string to the links that need encryption. You don't need to use the method if you use automatic encryption.

Download

QueryStringModule.zip (1,55 KB)

Tags:

ASP.NET

Comments

1/26/2007 7:26:25 PM #

 NTulip

While I find this to be a perfect solution to an existing issue, Have you considered running any tests to see how performance is affected by this?

NTulip |

1/26/2007 8:36:08 PM #

Mads Kristensen

I haven't run any performance tests, but I don't think it will have any negative impact on most websites.

Mads Kristensen |

1/27/2007 4:04:26 AM #

Marcus

Why wouldn't you just store in information in a Session level context?

Marcus |

1/27/2007 6:59:55 AM #

Mads Kristensen

Because session is a per-visitor store. QueryString encryption has nothing to do with the visitors, it is more along the lines of request obfuscation.

Mads Kristensen |

1/27/2007 10:36:41 AM #

 Adi

What happens if you get this request:

.....?enc=VXzal017xHwKKPolDWQJoLACDqQ0fE//wGkgvRTdG/GgXIBDd1&param2=value2

I would go for this one:

...yourRealOrMappedPath/VXzal017xHwKKPolDWQJoLACDqQ0fE//wGkgvRTdG/GgXIBDd1.aspx

but you'd have to somehow strip the / and \ chars from such an encrypted qs/file name.
The idea isn't bad at all. Let us know when you post v2.

Adi

Adi |

1/30/2007 1:46:53 AM #

 John Prado

Works like a charm.

I translate it to VB.Net:

Imports System
Imports System.IO
Imports System.Web
Imports System.Text
Imports System.Security.Cryptography

Public Class QueryStringModule
    Implements IHttpModule

    Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
    End Sub

    Public Sub Init(ByVal context As HttpApplication) Implements System.Web.IHttpModule.Init
        AddHandler context.BeginRequest, AddressOf context_BeginRequest
    End Sub

    Private Const PARAMETER_NAME As String = "enc="
    Private Const ENCRYPTION_KEY As String = "key"

    Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim context As HttpContext = HttpContext.Current
        If context.Request.Url.OriginalString.Contains("aspx") AndAlso context.Request.RawUrl.Contains("?") Then
            Dim query As String = ExtractQuery(context.Request.RawUrl)
            Dim path As String = GetVirtualPath
            If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
                Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
                Dim decryptedQuery As String = Decrypt(rawQuery)
                context.RewritePath(path, String.Empty, decryptedQuery)
            Else
                If context.Request.HttpMethod = "GET" Then
                    Dim encryptedQuery As String = Encrypt(query)
                    context.Response.Redirect(path + encryptedQuery)
                End If
            End If
        End If
    End Sub

    Private Shared Function GetVirtualPath() As String
        Dim path As String = HttpContext.Current.Request.RawUrl
        path = path.Substring(0, path.IndexOf("?"))
        path = path.Substring(path.LastIndexOf("/") + 1)
        Return path
    End Function

    Private Shared Function ExtractQuery(ByVal url As String) As String
        Dim index As Integer = url.IndexOf("?") + 1
        Return url.Substring(index)
    End Function

    Private Shared ReadOnly SALT As Byte() = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString)

    Public Shared Function Encrypt(ByVal inputText As String) As String
        Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged
        Dim plainText As Byte() = Encoding.Unicode.GetBytes(inputText)
        Dim SecretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
        ' Using
        Dim encryptor As ICryptoTransform = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16))
        Try
            ' Using
            Dim memoryStream As MemoryStream = New MemoryStream
            Try
                ' Using
                Dim cryptoStream As CryptoStream = New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
                Try
                    cryptoStream.Write(plainText, 0, plainText.Length)
                    cryptoStream.FlushFinalBlock()
                    Return "?" + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray)
                Finally
                    CType(cryptoStream, IDisposable).Dispose()
                End Try
            Finally
                CType(memoryStream, IDisposable).Dispose()
            End Try
        Finally
            CType(encryptor, IDisposable).Dispose()
        End Try
    End Function

    Public Shared Function Decrypt(ByVal inputText As String) As String
        Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged
        Dim encryptedData As Byte() = Convert.FromBase64String(inputText)
        Dim secretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
        ' Using
        Dim decryptor As ICryptoTransform = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16))
        Try
            ' Using
            Dim memoryStream As MemoryStream = New MemoryStream(encryptedData)
            Try
                ' Using
                Dim cryptoStream As CryptoStream = New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
                Try
                    Dim plainText(encryptedData.Length) As Byte
                    Dim decryptedCount As Integer = cryptoStream.Read(plainText, 0, plainText.Length)
                    Return Encoding.Unicode.GetString(plainText, 0, decryptedCount)
                Finally
                    CType(cryptoStream, IDisposable).Dispose()
                End Try
            Finally
                CType(memoryStream, IDisposable).Dispose()
            End Try
        Finally
            CType(decryptor, IDisposable).Dispose()
        End Try
    End Function
End Class

John Prado |

2/8/2007 7:42:05 AM #

 Mikael

This module works really nice, however the ACTION property of the asp form tags is not encrypted, is there any way to do that?

Mikael |

2/9/2007 5:57:00 AM #

Mads Kristensen

@Mikael: Sure, but it's not very obvious because of a bug in ASP.NET. You have to override the form control for it to work. Here is how to do it

madskristensen.dk/.../...SPNETForURLRewriting.aspx

Good luck with it

Mads Kristensen |

6/23/2007 12:01:58 AM #

Tyler

I've noticed that on postbacks the query string becomes decrypted, any ideas on what is causing this and how I might be able to fix it?

Any help is much appreciated, thanks.

Tyler Canada |

6/24/2007 8:18:50 PM #

Craig

I'm having the same problem as Tyler. The query string is encrypted during normal navigation but on postback it decrypts itself, negating the use of the entire module. I'm using the VB.net conversion of the posted code.

Craig South Africa |

6/29/2007 10:39:19 PM #

Tyler

I found a solution at
www.helicontech.com/forum/forum_posts-TID-6254.htm

basically you just add the following class,

namespace ActionlessForm {
  public class Form : System.Web.UI.HtmlControls.HtmlForm
  {
     protected override void RenderAttributes(HtmlTextWriter writer)
     {
        writer.WriteAttribute("name", this.Name);
        base.Attributes.Remove("name");

        writer.WriteAttribute("method", this.Method);
        base.Attributes.Remove("method");

        this.Attributes.Render(writer);

        base.Attributes.Remove("action");

        if (base.ID != null)
           writer.WriteAttribute("id", base.ClientID);
     }
  }
}
register it with your page,
<%@ Register TagPrefix="skm" Namespace="ActionlessForm" Assembly="ActionlessForm" %>

and replace your <form runat="server">, with: <skm:Form id="Form1" method="post" runat="server">
and the closing </form> with: </skm:Form>

works for me.

Tyler Canada |

7/3/2007 10:41:32 AM #

mani

module works fine for me.. Smile
me getting problem when trying to use it to paas on to file download page ... my file path is getting encrypted and decrypted as it should be but in file download dialog box, file names are getting changed like "a b c" to "a_b_c" after decryption.
is there any way to avoid this?




mani India |

7/12/2007 9:06:26 AM #

srik

this is what I am exactly searching for.. I have tested in my sample application,

i am getting the encrypted url like below:
someForm.aspx

it's working fine, but when I click a button in this page, the URL automatically (decrypting querystring) changing like how Iam getting previously:  http://someForm.aspx?userId=24

I am really stuck- have you got any idea why it's happening like this?

srik India |

8/24/2007 10:08:31 AM #

Gokhan Demir

hi !
For solving url decryption problem on postbacks ,
just change the code like below :

else if (context.Request.HttpMethod == "GET") ---> else if (context.Request.HttpMethod == "GET" || context.Request.HttpMethod == "POST")

I have made basic tests, it works like a charm !

thanks again mads Smile

Gokhan Demir Turkey |

8/28/2007 8:06:05 AM #

Keith Smith

The module works well to encrypt and decrypt automatically but it needs the ActionlessForm  code above to stop it decrypting on postback.  The vb code for this is below:

Namespace ActionlessForm
    Public Class Form
        Inherits System.Web.UI.HtmlControls.HtmlForm
        Protected Overrides Sub RenderAttributes(ByVal writer As System.Web.UI.HtmlTextWriter)
            writer.WriteAttribute("name", Me.Name)
            MyBase.Attributes.Remove("name")
            writer.WriteAttribute("method", Me.Method)
            MyBase.Attributes.Remove("method")
            Me.Attributes.Render(writer)
            MyBase.Attributes.Remove("action")
            If Not (MyBase.ID) Is Nothing Then
                writer.WriteAttribute("id", MyBase.ClientID)
            End If
        End Sub
    End Class
End Namespace

Works Ok after it had been compiled into ActionlessForm.dll by the sdk command prompt using the vbc compiler and then put into the bin directory of my project.

Keith Smith United Kingdom |

8/29/2007 4:12:41 PM #

Jeremy Coenen

@Gokhan - your solution seems to have issues - my values are not being saved on a postback when using your solution.

Is there a solution other than the Actionless form - I'd rather not have to change all of my form tags

Jeremy Coenen United States |

9/5/2007 7:46:58 PM #

Chris

Sorry, I am failing to see how the module automatically encrypts querystrings.  It seems that I have to call QueryStringModule.Encrypt(queryString) for any querystring displayed on a page.

The only automatic encryption that is done is when a page is requested that doesn't have an encrypted querystring, the browser is redirected to the encrypted version.  But that means that my page has all unencrypted querystrings in the html.  Hovering over a link displays the unencrypted querystring params.  I am missing something or did I get the wrong code?

Chris United States |

10/1/2007 6:34:38 PM #

Chetan A. Sharma

I am getting error in my web.config file stating could not load Module QueryStringModule. Could you please advice what may be the issue?

BTW, I have code converted to VB.NET

Thanks

Chetan A. Sharma |

1/10/2008 12:01:05 AM #

Jesse

put this in the page:

<script type="text/javascript">
try{document.forms[0].action=""}catch(ex){}
</script>

www.chenjiliang.com/.../View.aspx

Jesse United States |

1/11/2008 6:34:30 AM #

pingback

Pingback from domainforum.co.cc

Domain Forum  » Blog Archive   » HttpModule for query string encryption

domainforum.co.cc |

1/18/2008 11:15:16 AM #

gman

I am trying to run the VB version posted by John Prado, but after adding it to the App_Code folder and referencing the module in the Web.config file and then running it causes the following ASP error:



Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: The directory '/App_Code/' is not allowed because the application is precompiled.

[HttpException (0x80004005): The directory '/App_Code/' is not allowed because the application is precompiled.]
   System.Web.Compilation.CodeDirectoryCompiler.GetCodeDirectoryAssembly(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories, Boolean isDirectoryAllowed) +3542110
   System.Web.Compilation.BuildManager.CompileCodeDirectory(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories) +125
   System.Web.Compilation.BuildManager.CompileCodeDirectories() +525
   System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +448

[HttpException (0x80004005): The directory '/App_Code/' is not allowed because the application is precompiled.]
   System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +57
   System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +612
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters) +644

[HttpException (0x80004005): The directory '/App_Code/' is not allowed because the application is precompiled.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +3465427
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +69
   System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +279



The other modules in my site are compilel dll's in the bin directory. Is there any way for me to compile the QueryStringModule as  a dll, stick it into the bin directory, reference it in the web. config and still use it to do the encryption/decryption in my ASP page?

gman South Africa |

3/5/2008 5:31:17 PM #

Robin

Hey Mads,
   This module works fine but encryption does not work for post backs. Say when the Save Button is clicked the page post backs in this case how do we encrypt the query string because if we do a Response.Redirect then the Save button event is never fired.

Could be great if i could get a solution for it

Thanks
Robin

Robin India |

3/12/2008 3:50:57 PM #

Yasen

A nice solution is to use a Control Adapter to remove the action attribute from the form tag, as it is in the following article: weblogs.asp.net/.../...rewriting-with-asp-net.aspx

Yasen Bulgaria |

6/17/2008 3:13:32 PM #

krunal

i have used this module.

but not worked for me...

i have just configured it and it is encrypting existing querystring parameters.

but when it descrypts and do context.Reweitepath and redirect to particular page.

in that page, ni Request.QueryString["pid"] i am not getting this pid key.
i am getting "enc" parameter (the old one - encrypted querystring) only.

e.g.:

1) viewtenderdtls.aspx?pId=60106
2) viewtenderdtls.aspx?enc=aVduRnw2WfLfLJkNmg5Tj/kdhDsSvwEMbOIb0U1j9uE=
3) context.RewritePath(path, string.Empty, decryptedQuery);
   having, path = "viewtenderdtls.aspx"
           descryptedquery = pId=60106

now it redirects to viewtenderdtls page and in that page, on page load when i m checking value in Request.QueryString["pid"] i m getting null.
also, request.querystring contains enc=pwy%2fG4OkS+Q3D4JCGlr95+DL4jhEHu0QJpqOkEoQ0d4%3d

pls help.

Thanks & Regards,
Krunal

krunal India |

7/10/2008 4:04:10 PM #

glenukstis

QueryStringModule doesn't work on IIS7 Frown may someone know how to solve this problem?

glenukstis Lithuania |

7/16/2008 1:17:12 PM #

Krunal

Hi,

now, your module is working fine with my application.

But, i am getting error when drcrypting the url. pls help.

i am getting this querystring - y=YI2Cs3UsPCf8B%2fbiY9zTH0GVNLIBKO4SLKayezaR4QM%3d

rawquery = YI2Cs3UsPCf8B%2fbiY9zTH0GVNLIBKO4SLKayezaR4QM%3d

Now, the "%3d" kind of values creating problems and gives exception when decrypting.

i m stuck here.

thanks,
krunal

Krunal India |

8/12/2008 5:40:40 PM #

Steve B


This is the single most useful code i've seen in years. the implementation is truly fire and forget (apart from when messed up my web config and put the httpmodule entry in the wrong section).

Well done and thanks for your generous sharing !

Steve B Spain |

8/22/2008 12:48:12 PM #

Raju

hi frnz,
this code is working fine when encrypting the querystring,but when i was trying the decrypt the query string i'm getting the error like
'Invalid character in a Base-64 string.'...
can any one help me in this regard...

thanks,
rajjjjj

Raju India |

8/26/2008 8:24:56 PM #

trackback

Tools

Tools

The Luebbes: A Family Blog |

9/2/2008 3:54:50 PM #

Tim M

Raju,
Check that inputText pram ends with "=" in the Decrypt method. If not add it.

if (!inputText.EndsWith("="))
                inputText += "=";

Tim M United States |

9/11/2008 10:30:30 PM #

shifty

I am having trouble with postbacks.  I am trying to add it programmatically instead of the other two answers of adapter and actionless form.  Any ideas?

shifty Korea |

9/18/2008 10:46:49 AM #

Yasen

In order to make it work on IIS 7 you have to add the module declaration to the system.webServer section of your web.config file. The modules section should look like this:


<modules>
    <remove name="QueryStringModule" />
    <add name="QueryStringModule" type="QueryStringModule" />

    <remove name="ScriptModule"/>
    <add name="ScriptModule" preCondition="managedHandler"
        System.Web.Handlers.ScriptModule, System.Web.Extensions,
        Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>


Note: The remove tag needs to be there if the module is also declared in the httpModules section - that way it will work both on IIS 6 and IIS 7.

Yasen Bulgaria |

9/24/2008 9:15:14 PM #

jujubeans

How do you display the encrypted query string when the link is hovered over on originating page?

jujubeans United States |

9/26/2008 7:21:29 AM #

Pablo

I use this code to encrypt the url but the
default.aspx
string url = QueryStringModule.Encrypt("mensaje");            
            Response.Redirect("Mensaje.aspx?=url");


message.aspx has
  protected void Page_Load(object sender, EventArgs e)
        {          
            if (!Page.IsPostBack)
            {
                string cad = Request.QueryString["enc"];
                Label1.Text = cad;//QueryStringModule.Decrypt(cad);
            }
          
        }
cad always has a null value! why?

Pablo Argentina |

9/26/2008 8:43:24 AM #

Pablo

I understand now!!! decrypt is dont needed really...


in my default.aspx

            string mensaje = "Some string";
            string k = "Mensaje=" + mensaje;
            string url = QueryStringModule.Encrypt(k);
            
            Response.Redirect("Mensaje.aspx" + url);


in Mensaje.aspx

         if (!Page.IsPostBack)
            {
                
                Label1.Text = (Request.QueryString["Mensaje"]);
                
            }
and the URL I see  

http://localhost:8677/main/Mensaje.aspx?enc=TjCSd+eVrG3ErqujleRL3f7dSjKKa2pSqTnDhzmHbGMIAnXkkliMGgevL3UfRszmVJ3vDqJKDY1IZQShjZkS8UFq7oaFx4I9kG+5a3UwKeRHLYtuzHAGcjzizrgIfiXLeNwT4PYPH8EbYFO1gcutgg==

work like a charm!

PD: I am from Venezuela no Argentina.

Pablo Venezuela |

9/26/2008 9:22:12 AM #

Pablo

Problem, I have a simple button to redirect to other webform and when I mouse up I can see in the status bar my real message and without crypting

<a href="img526.imageshack.us/my.php target="_blank"><img src="img526.imageshack.us/.../dibujoox4.th.gif" border="0" alt="Free Image Hosting at www.ImageShack.us" /></a><br /><br /><a href="img604.imageshack.us/.../dibujoox4.gif" title="QuickPost"><img src="http://imageshack.us/img/butansn.png" alt="QuickPost" border="0"></a>

Pablo Venezuela |

10/23/2008 4:42:59 PM #

Raj


Hi All,

I am trying to use the code. I am having a gridview with  hyperlinks in all rows for a column and when I click the link it should load a new page and I send couple of values to the loaded page.For this I use HyperLink inside the GridView and in the property of NavigateUrl i use the following code,friends could any one help me in using QueryString.Encrpt method for the following code please.

NavigateUrl='<%# Eval("StudentId","~/DeclarationForm.aspx?StudentId={0}") %>'

thanks and regards

Raj

Raj United Kingdom |

12/2/2008 11:40:59 PM #

millitheKidd

Hello,
I am using the code to pass what I call a "token" to another ASP.Net page. It's working great to encrypt the data as in the code here:
Protected Sub btnNextPage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNextPage.Click
        If PeterBlum.VAM.Globals.Page.IsValid Then 'I'm using Peter Blum's validators.
            insertData() 'inserts data to a database
            Dim qStr As String = QueryStringModule.Encrypt(tkn) 'encrypt the contents of token
            Response.Redirect("employment.aspx" + qStr) 'I can hover over qStr here and it's showing as encrypted.
        End If
    End Sub
However, I don't know how to decrypt it on the next page and stick my value of token in a hidden field.
I've tried this on the next page:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
      Dim queryStr As String = QueryStringModule.Decrypt("qStr")
      tknUid.Text = queryStr 'tknUid is my hidden field or textbox I should say
    End If
End Sub
Any help would be GREATLY appreciated.
millitheKidd

millitheKidd United States |

12/4/2008 9:51:44 PM #

millitheKidd

Got it working,
and it's working pretty awesome! Here's what I did. Using John Prado's code above converted to VB.Net and doing something similar to what Pablo did, here is how mine looks.
On my first page I did this:
Protected Sub btnNextPage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNextPage.Click
        If PeterBlum.VAM.Globals.Page.IsValid Then  'using Peter Blum's validators @ www.peterblum.com
            insertData()  'inserts data to a database including my "token"
            Dim tknUI As String = tkn  'grab UserID and stick it in tknUI
            Dim id As String = "id=" + tknUI  'now concatenate tkn onto the end of "id"
            Dim url As String = QueryStringModule.Encrypt(id)  'now build the URL and encrypt it
            Response.Redirect("employment.aspx" + url)  'time to move to next page
        End If
End Sub
And on my next page:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       tknUid.Text = (Request.QueryString("id")) 'stick tkn into a hidden textbox
End Sub
Just in case you guys are wondering, I've created my token with this code. Feel free to use/share all you like. I hate to see people bang their head over a some piece of code.
Private Function CreateUserID()

        Dim str As New StringBuilder(Left(tbLastName.Text, 3))  'grab first 3 letters of client's last name
        Dim currentDate As Date = Now  'grab the date
        Dim [ReturnValue] As String

        str.Append(currentDate.ToString("MMMddyy"))  'date in this format DEC0408
        str.Append(Right(mstbSSN.Text, 4))  'grab last 4 of clients social security number
        str.Append(currentDate.ToString("hhmmssff"))  'grab time down to hundredths of a second 02122548 for 2:12 pm

        [ReturnValue] = str.ToString.ToUpper  'return things in UPPERCASE
        Return [ReturnValue]

End Function
What I'm doing here is creating a unique userid for our clients. Just a little way we're using to track users while they're filling out our web form. Then, in my Sub Routine I call it like this.
Protected Sub insertData()
tkn = CreateUserID()  'CreateUserID and stick it in the tkn varible to be picked up by the stored procedure.
'declare other variables and grab text properties from textboxes on my web form
End Sub
Maybe not the most efficient but it's working good for the moment. (-:

millitheKidd United States |

12/23/2008 2:09:48 PM #

James

Can this be made to work in cookieless is set to "true" for sessionstate in web.config

James India |

1/6/2009 2:12:07 PM #

Anders

Hey dude,

The download link is broken. Will you fix this??
Regards

Anders Denmark |

1/23/2009 2:15:33 PM #

Ahsan Arif

Hey Mads,
   This module works fine but encryption does not work for post backs. I am using AJAX tabs and when the "Move to step two" Button is clicked, the page post back occurs and end result will be a un-encrypted query string of next step.
Can any one help me in this regard.

Thanks
Ahsan Arif

Ahsan Arif India |

1/29/2009 6:31:58 PM #

mitoy75

Thanks for the code it works great!!  

mitoy75 United States |

1/30/2009 10:39:44 PM #

Mike Chevett

The "automatic" query string encryption is completely insecure.  The url doesn't get "automatically" encrypted until after a request has been made to the plaintext url.  This means that client has to know the plaintext url in order to make the request.  The browser doesn't display the plaintext url, but the browser certainly has the plaintext url.  Just open up fiddler and take a look at the 302's.  You will see the plaintext url.

This renders the encryption completely useless.

The QueryStringModule is still useful for automatically decrypting queryStrings, but it is up to the page developer to ensure that all queryStrings are manually encrypted.

I think the Repsonse.Redirect(...) should be removed from QueryStringModule because people may use that feature and assume that it is secure when it isn't at all.

Mike Chevett United States |

2/23/2009 9:29:03 AM #

Armin

Hi
Thanks a lot

Armin Iran |

3/6/2009 2:07:24 PM #

Jamie

Hi

How would I encrypt the querystring within a hyperlinkdata field within a gridview?

<asp:HyperLinkField Text="Edit" Target="_blank" DataNavigateUrlFields="PurchaseOrderId" DataNavigateUrlFormatString="~/editPO.aspx?Poid={0}" />

The user can see the unencrpyted querystring in the status bar when they hover over it.

I dont think I can do it code-behind.

Jamie United Kingdom |

3/13/2009 10:11:57 AM #

Ha Hanh Phuc

@Jamie: i think in ur situation, the code may be
<asp:HyperLinkField Text="Edit" Target="_blank" DataNavigateUrlFields="PurchaseOrderId" DataNavigateUrlFormatString="~/editPO.aspx?<%=QueryStringModule.Encrypt('Poid={0}')%>" />. Try it urself, i didn't test it.

Ha Hanh Phuc Vietnam |

3/21/2009 4:19:34 AM #

yuthear

Could anyone help me? I am having a problem when I use function descryption and then it appears the following:

System.FormatException: Invalid character in a Base-64 string.

yuthear Canada |

4/3/2009 11:48:33 PM #

cucsoi

i have problem: status bar always displays real URL, anyone helps me
thanks

cucsoi Vietnam |

9/7/2009 3:58:58 AM #

trackback

Variablen eines Querystringes verschl

Variablen eines Querystringes verschl

Christian |

9/7/2009 4:05:45 AM #

trackback

Variablen eines Querystringes verschlüsseln

Hier findet man eine Beschreibung wie man die Variablen eines Querystringes verschlüsseln kann, damit

SharePoint Blogs in German |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008