Encrypting and Decrypting Cookies in ASP.NET 2.0

After a complete reading you can encrypt/decrypt cookies in ASP.NET 2.0 and be sure that this article is targeted to ASP.NET 2.0 only. There is a class "CookieProtectionHelper", in "System.Web.Security" that is used internally (by the Framework) to encrypt cookies and is not accessible outside the library due to its protection level. Further, we are going to use this class using Reflection and access its methods namely "Encode" and "Decode".

The following class contains the two methods "Encrypt" and "Decrypt" that actually invoke the "Encode" and "Decode" methods of the "CookieProtectionHelper" class, respectively. And provide the facility to encrypt or decrypt a cookie.

  1. public static class CookieSecurityProvider  
  2. {  
  3.     private static MethodInfo _encode;  
  4.     private static MethodInfo _decode;  
  5.     // CookieProtection.All enables 'temper proffing' and 'encryption' for cookie  
  6.     private static CookieProtection _cookieProtection = CookieProtection.All;  
  7.   
  8.     //Static constructor to get reference of Encode and Decode methods of Class CookieProtectionHelper  
  9.     //using Reflection.  
  10.     static CookieSecurityProvider()  
  11.     {  
  12.         Assembly systemWeb = typeof(HttpContext).Assembly;  
  13.         Type cookieProtectionHelper = systemWeb.GetType(System.Web.Security.CookieProtectionHelper");  
  14.         _encode = cookieProtectionHelper.GetMethod("Encode", BindingFlags.NonPublic | BindingFlags.Static);  
  15.         _decode = cookieProtectionHelper.GetMethod("Decode", BindingFlags.NonPublic | BindingFlags.Static);  
  16.     }  
  17.   
  18.     public static HttpCookie Encrypt(HttpCookie httpCookie)  
  19.     {  
  20.         byte[] buffer = Encoding.Default.GetBytes(httpCookie.Value);  
  21.   
  22.         //Referencing the Encode mehod of CookieProtectionHelper class  
  23.         httpCookie.Value = (string)_encode.Invoke(nullnew object[] { _cookieProtection, buffer, buffer.Length });  
  24.         return httpCookie;  
  25.     }   
  26.   
  27.     public static HttpCookie Decrypt(HttpCookie httpCookie)  
  28.     {  
  29.         //Referencing the Decode mehod of CookieProtectionHelper class  
  30.         byte[] buffer = (byte[])_decode.Invoke(nullnew object[] { _cookieProtection, httpCookie.Value });  
  31.         httpCookie.Value = Encoding.Default.GetString(buffer, 0, buffer.Length);  
  32.         return httpCookie;  
  33.     }  
  34. } 

We're going to use this code. Create an ASP.NET 2.0 website and add a label to Default.aspx, as in:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.     <asp:Label ID="LabelPrice" runat="server" Font-Size="X-Large"></asp:Label>  
  10.     </form>  
  11. </body>  
  12. </html>  

Now, simply go to the code behind and write this code:

  1. using System;  
  2. using System.Web;
  3. public partial class _Default : System.Web.UI.Page  
  4. {  
  5.     protected void Page_Load(object sender, EventArgs e)  
  6.     {  
  7.         //Encrypting Cookie  
  8.         HttpCookie cookie = new HttpCookie("Price""$1700");  
  9.         cookie.Expires = DateTime.Now.AddDays(1);  
  10.         HttpCookie encodedCookie = CookieSecurityProvider.Encrypt(cookie);  
  11.         Response.Cookies.Add(encodedCookie);  
  12.   
  13.         //Method to decrypt cookie and show its value on the page  
  14.         GetOriginalCookie();  
  15.     }  
  16.   
  17.     private void GetOriginalCookie()  
  18.     {  
  19.         HttpCookie cookie = Request.Cookies["Price"];  
  20.         HttpCookie decodedCookie = CookieSecurityProvider.Decrypt(cookie);  
  21.         LabelPrice.Text = decodedCookie.Value;  
  22.     }  
  23. }

Run the application, you'll see the following result (the Cookie's encrypted value will be different):

cookieDemo.png

Note: There is some involvement (internally) of "MachineKey". If you don't specify one in the web.config file then it'll be generated randomly (different for each applications). So if you are sharing a cookie among multiple websites then you need to manually generate the Machine Key and add it to the web.config in all websites sharing the keys. In case you don't use a similar MachineKey in all applications then a cookie encrypted in one application can't be decrypted in another application.

Warning: It may possible that you are already using MachineKey for other tasks. So be careful and backup your data before changing anything in an existing application.

To learn more about MachineKey click here and to learn how to generate a MachineKey click here.


Similar Articles