Encrypting cookies with ASP.NET

Created 19 May 2009 13:59
I hadn't noticed it before, but ASP.NET provides a really simple way to encrypt your cookies. Cryptography is a field best left to the expert, but for simple encryption purposes this method is perfectly adequate.

First off, you will need to add an entry to your machine/web.config:
    validation="SHA1" decryption="AES" />
You can then encrypt/decrypt as follows:
  // encryption
  var ticket = new FormsAuthenticationTicket(2, "", DateTime.Now, DateTime.Now.AddMinutes(10), false, "mycookievalue");
  var encryptedData = FormsAuthentication.Encrypt(ticket);

  // decryption
  string myValue = FormsAuthentication.Decrypt(encryptedData).UserData.ToString();