Way to Encrypt Cookies with ASP.NET

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.

Way 1:

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.

Using HttpSecureCookie is easy to encrypt the cookie information.

HttpCookie cookie = new HttpCookie("UserName", "Terminator");
cookie.Expires = DateTime.Now.AddDays(1);
HttpCookie encodedCookie = HttpSecureCookie.Encode(cookie);
Response.Cookies.Add(encodedCookie);


To decode an encoded cookie:

HttpCookie cookie = Request.Cookies["UserName"];
lblDisplayBefore.Text = cookie.Value;
HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);


Note: To use HttpSecureCookie on a web farm, you need to set the correct MachineKey configuration in Web.Config.

Way 2:

We can also secure our cookie by using HttpCookieEncryption class.

You basically reference the DLL or include the code in your project. The HttpCookieEncryption type was rooted into the System.Web namespace.

Simply make a call to HttpCookieEncryption.Encrypt to encrypt the specified cookie. Note that the second overload to Encrypt actually modifies the Response, whereas the first does not.

On the next request, you can decrypt the encrypted cookie by calling HttpCookieEncryption.Decrypt(). This retrieves the specified cookie and returns a new instance with the decrypted value. Neither of the Decrypt methods modify the cookie in the current Response.

HttpCookie myEncryptedCookie =
HttpCookieEncryption.Decrypt(this.Context,"myEncryptedCookie");
if(myEncryptedCookie==null)
{
HttpCookie test = Response.Cookies["myEncryptedCookie"];
test["key1"]="value1";
test["key2"]="value2";

HttpCookieEncryption.Encrypt(this.Context,"myEncryptedCookie");

HttpCookie decrypted = HttpCookieEncryption.Decrypt(this.Context,
"myEncryptedCookie");

if(test["key1"].Equals(decrypted["key1"]) &&
test["key2"].Equals(decrypted["key2"]))
else
// Never happen
}


Hope we could have got something about securing Cookies.

Comments

Popular posts from this blog

Interview Questions to Ask the Employer

Place .NET DLL in GAC

Windows Communication Foundation - FAQ