Encryption of Form Field Data

How to encrypt hidden form field data in .NET

My article on Throttling Requests got quite a bit of attention, so I thought I would continue the security theme and show you a simple method of automatically encrypting hidden form fields that you don't want the user to be able to change, or know the value of. I will be making use of an extension to the HtmlHelper, a custom ModelBinder to handle the decryption and also Rijndael encryption to secure your data (you could use any method of encryption you so desire).

I must stress that this is simply one measure to ensure the security of your data, you should always still be validating the action at the code and finally database level, to ensure you have a secure application!

Example

A really simple example of this would be on a CMS system, lets say user can only edit posts that they created. You may have something like this in your view:

<%Using Html.BeginForm  %>
    <%:Html.HiddenFor(Function(m) m.DatabaseID)%>
    <!-- Other Editing fields here-->
    <input type="submit" value="Submit!" />
<%end using %>

If we inspected the code that is generated, we would get this:

<form action="/Home/Test" method="post">
    <input data-val="true" id="DatabaseID" name="DatabaseID" type="hidden" value="2012" />
    <input type="submit" value="Submit!" />
</form>

As you can quite clearly see, the database ID is 2012, and I could quite easily edit it to be able to submit against say, record 2013, which was posted by another user, if (god forbid) there was nothing checking in the back end that the user posting back actually has permissions to edit the post, you could malliciously edit other peoples data.

Rijndael

As I mentioned previous, I am going to be using Rijndael to handle my encryption, I'm not going to post all of the code here, you can use any encryption method you want, I personally grabbed this example, and made a few modifications to suit. Make sure you have a suitable encryption class in your project before you read past here!

Encryption

The first thing we want to do is create the part which handles encryption. We want to simply be able to replace the "HiddenFor()" with "EncryptedFor()". To do this we need to create a HtmlHelper extension which accepts a Linq expression of the targeted field, so it works in much the same way as HiddenFor.

''' <summary>
''' Creates an encrypted version of the field
''' </summary>
<System.Runtime.CompilerServices.Extension> _
Public Function EncryptedFor(Of TModel, TProperty)(htmlHelper As HtmlHelper(Of TModel), expression As Expression(Of Func(Of TModel, TProperty))) As MvcHtmlString
    Dim name As String
    If TypeOf expression.Body Is MemberExpression Then
        name = DirectCast(expression.Body, MemberExpression).Member.Name
    Else
        Dim op = (CType(expression.Body, UnaryExpression).Operand)
        name = DirectCast(op, MemberExpression).Member.Name
    End If
 
    'Get the value, and then encrypt it
    Dim value = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData)
    Dim encvalue = RijndaelSimple.Encrypt(value.Model, HttpContext.Current.User.Identity.Name)
    Return New MvcHtmlString("<input type=""hidden"" name=""" & name & "-encrypted"" value=""" & encvalue & """>")
End Function

So now, if we go back to our form, we should be able to switch to EncryptedFor, which will generate the hidden field:

<form action="/Home/Test" method="post">
    <input type="hidden" name="DatabaseID-encrypted" value="3JSlRkRb98Ow11HkGRb1XQ==">
    <!-- Other Editing fields here-->
    <input type="submit" value="Submit!" />
</form>

As you can see, the field name has been appended with "-encrypted", and the value is the encrypted string.

Decryption

The next thing we need to do is to handle the decryption and setting of the value. The MVC model binder will obviously not know that the field "DatabaseID-encrypted" is actually for the field "DatabaseID". What we need to do is create a custom model binder, which looks for the field in the Request.Form, decrypts it, and then sets the property.

Public Class EncryptedModelBinder
    Inherits DefaultModelBinder
 
    Protected Overrides Sub BindProperty(controllerContext As ControllerContext, 
                                         bindingContext As ModelBindingContext, propertyDescriptor As System.ComponentModel.PropertyDescriptor)
 
        If propertyDescriptor.Attributes.OfType(Of EncryptedAttribute)().Count > 0 Then
            'Look for the encrypted field
            If controllerContext.HttpContext.Request.Form(propertyDescriptor.Name & "-encrypted") IsNot Nothing Then
                Dim decvalue = controllerContext.HttpContext.Request.Form(propertyDescriptor.Name & "-encrypted")
                decvalue = RijndaelSimple.Decrypt(decvalue, "Some unique key")
                propertyDescriptor.SetValue(bindingContext.Model, If(IsNumeric(decvalue), CInt(decvalue), decvalue))
                MyBase.BindProperty(controllerContext, bindingContext, propertyDescriptor)
            End If
        Else
            'Normal binding
            MyBase.BindProperty(controllerContext, bindingContext, propertyDescriptor)
        End If
 
    End Sub
End Class

You'll notice here that I am looking for an EncryptedAttribute. This is because we want to prevent people just inspecting the code and posting back to the database ID. We decorate the properties that are expected to be encrypted with a simple attribute which basically says "Only set me using the -encrypted post back value, ignore anything else"

Public Class EncryptedAttribute
    Inherits Attribute
End Class

We just need to register this in our Gloabl.asax.vb file as well:

ModelBinders.Binders.DefaultBinder = New EncryptedModelBinder

And that's it!

The Result

I created a simple method which dumps out the request.form contents from the post back, and also outputs the value of the field. As you can see the encrypted value was passed back, but the property has correctly been set!

Content of the request.form: 
DatabaseID-encrypted: SVwvHJ8kzCeIjIN4VZeJLw==
 
The DatabaseID on the model is set to: 2012

Conclusion

The aim of this article was to give you another tool to secure your websites, and that's all it is, a tool. You should be secure your website every step of the way! As usual, any questions, please leave a comment.