views:

337

answers:

3

Hi everyone! How can I encrypt a cookie in a direct and simple way?

Thanks!!

+2  A: 

The simplest way will be to not encrypt it! Just use the cookie ID (plus a salt) to look up the values (contents) on the server.

+4  A: 

You probably shouldn't be doing this. If the cookie is sensitive, store it only on the server.

If you really need to, there are a number of ways to do it. First, you will need to convert the plaintext to a byte array, like this:

var plainBytes = Encoding.UTF8.GetBytes(plaintext);

If you're sure that your plaintext will never use Unicode, you can use Encoding.ASCII instead; this will result in a smaller cookie).

Then, you will need to encrypt it. The easiest way to do that is to use DPAPI, like this. (First, add a reference to System.Security.dll). Note that this will not work on a server farm.

var encryptedBytes = ProtectedData.Protect(plainBytes, null, DataProtectionScope.CurrentUser);

Finally, you need to convert it back to text so you can put it in the cookie. This is best done in Base64, like this:

Response.AddCookie("MyEncryptedCookie", Convert.ToBase64String(encryptedBytes));


To decrypt the cookie, you'll need to reverse these steps, like this:

var encryptedBytes = Convert.FromBase64String(Request.Cookies["MyEncryptedCookie"].Value);
var decryptedBytes = ProtectedData.Unprotect(encryptedBytes , null, DataProtectionScope.CurrentUser);
var plaintext = Encoding.UTF8.GetString(decryptedBytes);

Note that the cookie will be very large, even for small plaintexts.

If you want to use this on a server farm, you can use AES; look at System.Security.Cryptography.RijndaelManaged.

SLaks
Thanks SLaks! I will use something like RijndaelManaged! :-)
AndreMiranda
Is there a reason that you cannot store it in session state?
SLaks
A: 

The most secure way to do this is to use ASP.Net session state instead of cookies. Since session state is never sent to the client, you will have nothing to worry about.

SLaks