I really have some good laughs when I tamper with cookies on my machine and watch the results when it is submitted back to the site. On the other hand, I don�t want any one to do the same to the cookies that I make!
Cookies, most of the times, shouldn�t be in plain text, at least, they should be tamper-proof! Revealing the content of your cookies might give curious and malicious people an idea about your application�s architecture, and that might help hacking it.
ASP.NET encodes and hashes its authorization ticket, making it secure and tamper-proof. However, the methods used to secure authorization cookies are inaccessible from outside the .NET framework libraries, so you can�t protect your own cookie using these methods; you need to protect it yourself using your own encryption key, encoding and hashing algorithms.
HttpSecureCookie works around this by accessing the same methods ASP.NET uses for cookie authorization.
Of course, you shouldn�t save valuable information in your cookies, but if you have to, then this library is at your disposal.
Before you start using this code, if you do not know what
MachineKey is, I highly recommend checking this MSDN article: How To: Configure MachineKey in ASP.NET 2.0.
ASP.NET uses the
System.Web.Security.CookieProtectionHelper internal class to decode and encode the content of a cookie before submitting it to the client. This class is based on the
MachineKey. I wonder why Microsoft kept this class internal!?
To be able to access this internal class, I had to use reflection to be able to access the
Encode methods of
Eric Newton has a similar and good article on CP: Encrypting cookies to prevent tampering. However, that code is made for .NET 1.1 and it doesn’t work with .NET 2.0 (but it does with some modifications); moreover, its resulting cipher text is in binary format versus being in encrypted format, and I don’t know if this is a security risk. Also, I am accessing a higher level class
System.Web.Security.CookieProtectionHelper than the one used by that article,
System.Web.Configuration.MachineKey, to obtain the cryptography service, and that saved me time by not writing some low level code.
There is also another available method for encoding cookies, by using the
FormsAuthentication.Encrypt; for more information, check the section "Creating the Forms Authentication Cookie" on Explained: Forms Authentication in ASP.NET 2.0. However, I believe, the method mentioned in this article is more flexible.