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.

Leave a Comment