ASP.NET ViewState data is stored in a single Base64-encoded string such as this:
Since this value is not formatted in clear text, developers sometimes assume that their ViewState data is encrypted which is most certainly not the case. This data string can be reverse-engineered this and then viewed. This is an obvious security issue if sensitive data is being stored in ViewState.
To make ViewState secure, there are two choices, hash codes and ViewState encryption.
Use a hash code.
A hash code is a cryptographically strong checksum. When you use a has code, ASP.NET calculates the checksum based on the current ViewState content data and then adds this to the hidden input field when the page when is returned to the client. On the page post back, ASP.NET then recalculates the checksum to ensures a match. If a malicious user were to change the ViewState data, ASP.NET can detect the the change reject the postback.
Hash codes are enabled by default, however, sometimes developers elect to disable hash codes to prevent problems on a web farm when servers have different keys. Hash codes can be disabled on the page in the .aspx file’s Page directive:
<%@ Page EnableViewStateMac="false" ... %>
To disable hashing site-wide use the ViewStateMac attribute of the pages element in web.config :
<configuration> <system.web> <pages enableViewStateMac="false" /> ... </system.web> </configuration>
For more on hashing, please refer to C# Security – Hashing
Use ViewState Encryption.
Hash codes help to prevent ViewState data from being tampered with but they do not provide much assistance in preventing ViewState data from being read since hash codes can still be converted to clear text. To prevent ViewState being read, use the ViewState Encryption, which can be turned on at the page level using the ViewStateEncryptionMode property of the Page directive:
<%@Page ViewStateEncryptionMode=”Always” … %>
Or site-wide in the web.config file:
<pages viewStateEncryptionMode=”Always” />
There are three settings for viewStateEncryptionMode:
- Always : All ViewState data is encrypted.
- Never : No ViewState data is encrypted.
- Auto : Data is only encrypted when specifically requested by the ASP.NET control.
The default setting is Auto so no data will be encrypted unless otherwise requested by a control on a page. For a control to request encryption in needs to call the Page.RegisterRequiresViewStateEncryption() method before it is rendered to HTML.
Note that using encryption incurs a performance penalty so it should only be used when necessary.