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.
public static class CookieSecurityProvider
{
private static MethodInfo _encode;
private static MethodInfo _decode;
// CookieProtection.All enables 'temper proffing' and 'encryption' for cookie
private static CookieProtection _cookieProtection = CookieProtection.All;
//Static constructor to get reference of Encode and Decode methods of Class CookieProtectionHelper
//using Reflection.
static CookieSecurityProvider()
{
Assembly systemWeb = typeof(HttpContext).Assembly;
Type cookieProtectionHelper = systemWeb.GetType(System.Web.Security.CookieProtectionHelper");
_encode = cookieProtectionHelper.GetMethod("Encode", BindingFlags.NonPublic | BindingFlags.Static);
_decode = cookieProtectionHelper.GetMethod("Decode", BindingFlags.NonPublic | BindingFlags.Static);
}
public static HttpCookie Encrypt(HttpCookie httpCookie)
{
byte[] buffer = Encoding.Default.GetBytes(httpCookie.Value);
//Referencing the Encode mehod of CookieProtectionHelper class
httpCookie.Value = (string)_encode.Invoke(null, new object[] { _cookieProtection, buffer, buffer.Length });
return httpCookie;
}
public static HttpCookie Decrypt(HttpCookie httpCookie)
{
//Referencing the Decode mehod of CookieProtectionHelper class
byte[] buffer = (byte[])_decode.Invoke(null, new object[] { _cookieProtection, httpCookie.Value });
httpCookie.Value = Encoding.Default.GetString(buffer, 0, buffer.Length);
return httpCookie;
}
}
We're going to use this code. Create an ASP.NET 2.0 website and add a label to Default.aspx, as in:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="LabelPrice" runat="server" Font-Size="X-Large"></asp:Label>
</form>
</body>
</html>
Now, simply go to the code behind and write this code:
using System;
using System.Web;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Encrypting Cookie
HttpCookie cookie = new HttpCookie("Price", "$1700");
cookie.Expires = DateTime.Now.AddDays(1);
HttpCookie encodedCookie = CookieSecurityProvider.Encrypt(cookie);
Response.Cookies.Add(encodedCookie);
//Method to decrypt cookie and show its value on the page
GetOriginalCookie();
}
private void GetOriginalCookie()
{
HttpCookie cookie = Request.Cookies["Price"];
HttpCookie decodedCookie = CookieSecurityProvider.Decrypt(cookie);
LabelPrice.Text = decodedCookie.Value;
}
}
Run the application, you'll see the following result (the Cookie's encrypted value will be different):
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.