Monday, April 7, 2014

ASP.NET Membership Encryption and View State Encryption/Validation

When using .NET's Membership provider to implement Forms Authentication in your application, the user names and passwords are encrypted in the database (aspnet_Membership) table.  You must specify the encryption method and a key to perform the encryption and decryption in the web.config file.  This is where this is specified:

<system.web>
    <machineKey decryptionKey="YOUR KEY GOES HERE" decryption="AES" />
<system.web />

Despite the name, the decryption and decryptionKey attributes are not only used for decryption but are also used for encryption.  This tells Membership how to encrypt passwords and usernames in the database.  It will also tell ASP.NET how to encrypt the View State if you are configured to encrypt the View State.  This decryption attribute is set to AES.  This is the standard for encryption at the time of this writing.  In fact the decryption attribute's default is AES.  Triple DES (3DES) is also acceptable if you have older DES stuff.

How do you generate a decryptionKey?  Click on the application in IIS, and double click the Machine Key icon.  Here you can select the Generate Keys option on the right to generate a key for you.  If you click Apply, it will update the machineKey node in the web.config file with the information.

The validation and validationKey attributes are only used to validate the View State.  A hash value is created by using the validationKey and the hash function specified by the validation attribute.  This hash value is compared to what it initially was when it was sent by the browser to what is is when the server receives it.  If they are different, then the server knows that the View State was tampered with.  The validation attribute is set to "SHA1" by default.  You don't necessarily need to generate a validationKey.  ASP.NET can generate one each time a request is made.  However, if you have multiple load balanced web servers, then you must generate a validationKey so that the servers can share the Session Id.  You would follow the same procedure in IIS to generate a validationKey if you so desire.  Here is an example of the machineKey node with both validation and decryption attributes configured.

<system.web>
    <machineKey validationKey="YOUR KEY GOES HERE" 
        decryptionKey="YOUR KEY GOES HERE" decryption="AES" validation="SHA1" />
<system.web />

How to encrypt the View State

No comments:

Post a Comment