The ASP.NET ViewState is a client side state management mechanism. The ViewState is stored in a hidden field with an ID __VIEWSTATE. Typically, stored ViewState information looks like:
__VIEWSTATE
Now let us look at the value. It looks likes an encrypted string. 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:
But people often get confused that this is an encrypted string.
Let us try to decode the string using ViewState Decoder (a nice tool created by Fritz Onion).
After decoding the string, we can see the exact data that is stored inside the ViewState.
You can write a few lines of code to decode the text and you will get the actual View State information.
So here is how the ViewState works:
By default, ViewState is serialized into a Base-64 encoded string. On postback, the ViewState information is loaded and reapplied to the persisted state of the control in the control hierarchy.
There are two different ways in which you can prevent someone from decrypting ViewState data.
EnableViewStateMAC=true
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.
EnableViewStateMac="True"
ViewStateEncryptionMode="Always"
ViewStateEncryptionMode has three different options that can be set:
ViewStateEncryptionMode
Always
Auto
Page.RegisterRequiresViewStateEncryption()
Never
If you set ViewStateEncryptionMode="Always" and try to decode ViewState data, you will get information as shown below:
We can also enable these settings for EnableViewStateMAC and ViewStateEncryptionMode in web.config:
EnableViewStateMAC
Note: Try to avoid ViewState encryption if it is not necessary as it can cause performance issues.
If you are a beginner to ViewState, please read my article on ViewState – Beginner’s Guide to View State.