03 June 2016

Encrypt ViewState info

View State:
The ViewState is used in retaining values between multiple requests for the same page. Viewstate is stored on page it self in encoded form. When an ASP.NET page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. If the data is too long for a single field, then ASP.NET performs view state chunking (new in ASP.NET 2.0) to split it across multiple hidden fields. The following code sample demonstrates how view state adds data as a hidden form within a Web page’s HTML:


<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE” value="/wEPDwUKMTIxNDIyOTM0Mg9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzQvNS8yMDA2IDE6Mzc6MTEgUE1kZGROWHn/rt75XF/pMGnqjqHlH66cdw==" />


The ViewState is stored in a hidden field with an ID __VIEWSTATE. This is nothing but a Base64 encoded string, and is not an encrypted string. So it can be easily decoded.


The main reasons for using Base64 encoding are as follows:




  1. Base64 makes a string suitable for HTTP transfers

  2. It makes it a little harder to read


But, after decoding the string (viewstate data), we can see the exact data that is stored inside the ViewState.


Solution


There are two different ways in which you can prevent someone from decrypting ViewState data.




  1. You can make sure that the ViewState information is tamper-proof by using "hash codes". You can do this by adding EnableViewStateMAC=true in your page directive. MAC stands for "Message Authentication Code".


When we use EnableViewStateMac="True", during ViewState save, ASP.NET internally uses a hash code. This hash code is a cryptographically strong checksum. This is added with the ViewState content and stored in a hidden filed. During postback, the checksum data is verified again by ASP.NET. If there is a mismatch, the postback will be rejected.




  1. The second option is to set ViewStateEncryptionMode="Always" with your page directives. This will encrypt the ViewState data.


ViewStateEncryptionMode has three different options that can be set:




  • Always: encrypt the View State always.

  • Auto: encrypt if a control requests for encryption. For this to happen, the control must call thePage.RegisterRequiresViewStateEncryption() method.

  • Never: Never encrypt the ViewState.


<system.web>
<pages enableViewStateMac="true">
                viewStateEncryptionMode="Always">
</pages>
</system.web>

No comments: