Securing ViewState in ASP.Net

We need to do is to add encryption to the ViewState. This is done by editing the web.config only. We need to tell the web application to enable ViewStateMac. This will generate a hashed code and add it to the ViewState. If the hashcode is tampered with, any postback will fail.

Tamper-Proofing

A hashcode will not secure the actual data within the ViewState field, but it will greatly reduce the likelihood of someone tampering with ViewState to try to spoof your application, that is, posting back values that your application would normally prevent a user from inputting.

You can instruct ASP.NET to append a hashcode to the ViewState field by setting the EnableViewStateMAC attribute:

<%@Page EnableViewStateMAC=true %>

EnableViewStateMAC can be set at the page or application level. Upon postback, ASP.NET will generate a hashcode for the ViewState data and compare it to the hashcode store in the posted value. If they don't match, the ViewState data will be discarded and the controls will revert to their original settings.

By default, ASP.NET generates the ViewState hashcode using the SHA1 algorithm. Alternatively, you can select the MD5 algorithm by setting <machineKey> in the machine.config file as follows:

<machineKey validation="MD5" />

Encryption

You can use encryption to protect the actual data values within the ViewState field. First, you must set EnableViewStatMAC="true", as above. Then, set the machineKey validation type to 3DES. This instructs ASP.NET to encrypt the ViewState value using the Triple DES symmetric encryption algorithm.

<machineKey validation="3DES" />
Tags: ,
Hot on Web:


About author