Sometimes its the basic things that we tend to forget. It’s true. One example is encrypting the ViewState. Someone asked me this question today and I had to admit that I wasn’t able to answer on top of my head. Whats funny is that I’ve been doing it all along but never told myself to remember how.
Anyhow, lets go back to the topic on how to encrypt the ViewState in ASP.NET.
Prior to .NET 2.0 the way you would do this is via the machineKey element validation attribute. In .NET 2.0 onwards Microsoft provided us with an option to specify ViewState encryption in the page level or web.config level via the ViewStateEncryptionMode attribute.
ViewStateEncryptionMode has three enumeration values that you could use defending on what you need. They are Auto, Never and Always. ViewStateEncryptionMode.Auto means that the page will be encrypted if a control request for encryption. By default the value for ViewStateEncryptionMode is set to Auto. ViewStateEncryptionMode.Never means that ASP.NET will not encrypt the ViewState on your page even if a control request for it. This is a good bypassing mechanism if and only if you know that the page does not need to have ViewState encryption on it. ViewStateEncryptionMode.Always on the otherhand will encrypt your page all the time. A good practice for pages with sensitive information is to always set this ViewStateEncryptionMode to Always as you don’t want anybody compromising your ViewState.
To enable ViewState encryption in the page all you need to do is specify the value for ViewStateEncryptionMode at the Page directive
<%@Page ViewStateEncryptionMode=”Always” %>
To enable ViewState encryption via web.config to apply to the whole application
<pages ViewStateEncryptionMode=”Always” />
One thing to remember though is that you can’t set ViewStateEncryptionMode via code
To request for ViewState encryption inside a control all you need to do is call RegisterViewStateEcryption() method from the Page class
protected override void OnInit(EventArgs e)
if(Page != null)
Ahhh, such reverie. Now I need to remember this for future use (or questions). Cheers!