Encrypted Cookie

You can use encrypted cookies when you want to store some sensitive info in the user cookie. Of course, you should avoid storing such info in the client but in some cases it can act as a cache or a temporary client storage that you want to be private.
An encrypted is safer than a simple cookie but that doesn't mean you can skip the SSL. In fact for maximum protection use both SSL and encrypted cookies with custom encryption.

I repeat, you should avoid storing sensitive information in a cookie, encrypted or not. However if you need more secure cookies, this class makes it easy for you to use them.

//get encrypted cookie from request by name.  if the cookie is not found, a new one is created
var cookie = EncryptedCookie.FromRequest(Request.Cookies, "MyCookie", "12345678"); 

//create new cookie with name and secret, using the default cookie encryption
var cookie = new EncryptedCookie("MyCookie","12345678");

 //we open it. if it is a new cookie you can skip this step

//read some values (if any)
var info=cookie.GetValue("role", "anonymous"); // returns the role or anonymous if key not found
int number= cookie.GetValue("number",3); //returns the number stored or 3 if key doesn't exist

//set some values
cookie["role"] ="admin"; 

//we seal it and send it to response. after that, nothing can be add/retrieved/modified from the cookie value.

Last edited Feb 2, 2011 at 3:18 PM by mike_sapiens, version 1


No comments yet.