Encrypt cookies in ASP.NET Encrypt cookies in ASP.NET asp.net asp.net

Encrypt cookies in ASP.NET


You don't need to roll your own any more.

.Net 4.5 has MachineKey.Protect() and MachineKey.Unprotect().

System.Web.Security.MachineKey

.Net 4.0 has MachineKey.Encode() and MachineKey.Decode(). You should just set the MachineKeyProtection to 'All'. These are now obsolete though and you should use the newer ones if you have 4.5.

Note if you try and use these in something like a console app instead of ASP.Net it seems to generate a new key with every app restart. I only checked it quickly but in ILSpy it looks like it generates its own defaults if the appropriate app.setting are missing.

I haven't been able to find a non-ASP.Net equivalent.


Why not just use the encryption found in System.Security.Cryptography to encrypt and decrypt the cookie name and value when it's sensitive? You can write some utility functions to manage it pretty easily. Example utility functions:

private static void SetEncryptedCookie(string name, string value){    var encryptName = SomeEncryptionMethod(name);    Response.Cookies[encryptName].Value = SomeEncryptionMethod(value);    //set other cookie properties here, expiry &c.    //Response.Cookies[encryptName].Expires = ...}private static string GetEncryptedCookie(string name){    //you'll want some checks/exception handling around this    return SomeDecryptionMethod(               Response.Cookies[SomeDecryptionMethod(name)].Value);}