Is ViewState safe

Viewstate is a convenient way to keep the page information. This happens via the hidden field __Viewstate. The details can be found elsewhere in Devtrain.

<input type="hidden" name= "__VIEWSTATE"value="dDw3NDg2NTI5MDg7Oz4=" />

If you now look at a web page in source code, you will not be able to read the original content of the viewstate field.
Now it seems reasonable to conclude that this was achieved through encryption. This is also only true the key is more known as global. It is Base64 encoded. This is only so that no values ​​can be lost on the round trip. In such a viewstate, any kind of character can be found and depending on the encoding of the browser or server, they can be lost in response or request.

The gap is recognized, now we turn to the plugging of the hole. But security is not absolute. No system is safe. The more security, the more effort has to be made.
First of all, there is the obvious danger that someone will intrude on the response and submited falsified data. This could be solved, for example, by querying the Broeser's IP address.

Again, this does not work well if the browser is behind a proxy.
The best thing to do is to use the ASP .NET on-board tools and save yourself the work. The feature is called VievstateMAC and uses the MAC address to identify which is uniquely bound to the network card worldwide. You can activate this in the page or for the entire application.

In the Page, as usual, the Page directive must be used.

<%@Page EnableViewStateMac=true%>

To set the ViewStatMAC for the entire application, as always Web.Config and here the Section Pages. Pay attention to the correct spelling!

<pages enableViewState="true" enableViewStateMac="true"/>

For this, ASP .NET appends a hascode to the viewstate info and can thus recognize whether it is the original. Here the viewstate from the same page as above.

<input type="hidden" name= "__VIEWSTATE"value="dDw3NDg2NTI5MDg7Oz49UF+HpvMzr9XNq5FXpkENqgS2WA==" />

This hash code is encrypted by standard with SHA1. If you want to use a different key, you can set this via the machine.Config.

<machineKey validation="MD5">

Here is the original section from the machine.Config file

<!--  validation="[SHA1|MD5|3DES]" -->
   
validationKey = "AutoGenerate"
decryptionKey = "AutoGenerate"
validation = "SHA1" />

The bytes from the viewstate can also be encrypted using the same method. To do this, set the validation to 3DES.

<machineKey validation="3DES">

You can also set the key yourself. The longer the safer. The maximum length is 128 characters. However, this also requires significantly more computing power on the server.

<machineKey validation="SHA1" ValidationKey="3454a34f34e678b9cef....">

Keys can be created with the System.Security.Cryptography class. You will find details on this in a later article.