Click here to Skip to main content
15,884,237 members
Articles / Web Development / ASP.NET

Additional functionality for ASP.NET 2.0's CookieParameter

Rate me:
Please Sign up or sign in to vote.
3.33/5 (3 votes)
6 Nov 20042 min read 57.5K   440   15  
This article addresses some missing functionality in ASP.NET 2.0's CookieParameter type, including getting a multi-valued cookie Key value and providing some HttpCookieEncryption support.
using System;
using System.Web;
using System.Web.Configuration;
using System.Security.Cryptography;

using Ensoft.Web.Configuration;

namespace System.Web
{
	/// <summary>
	/// Provides methods for Encrypting and Decrypting Cookies.
	/// </summary>
#if FRAMEWORK_2_0
	public static class HttpCookieEncryption
	{
#else
	public /*static*/ class HttpCookieEncryption
	{
		// static classes have no constructor
		private HttpCookieEncryption()
		{
		}
#endif

		/// <summary>
		/// Decrypts the cookie.
		/// </summary>
		/// <param name="cookie">The cookie to decrypt.</param>
		/// <returns>An cloned HttpCookie instance with the Value decrypted.</returns>
		public static HttpCookie Decrypt(HttpCookie cookie)
		{
			if(cookie==null) throw new ArgumentNullException("cookie");

			//nothing to do!
			if(cookie.Value.Length==0) return cookie;

			try
			{
				byte[] encrypted = MachineKeyWrapper.HexStringToByteArray(cookie.Value);
				if (encrypted == null) return null;	// i wonder if this is the most intuitive situation here... the above method will return null if it cant "DeHex" the string...
				byte[] decrypted = MachineKeyWrapper.EncryptOrDecryptData(false, encrypted, null, 0, encrypted.Length);

				//i wonder if I should guarantee getting a cookie at this point [no exceptions, etc]
				HttpCookie decryptedCookie = CloneCookie(cookie);
			
				decryptedCookie.Value = System.Text.Encoding.Unicode.GetString(decrypted);

				return decryptedCookie;
			}
			catch(Exception ex)
			{
				//repackage the exception
				throw new HttpException("Unable to Decrypt the cookie.", ex);
			}		
		}
		/// <summary>
		/// Retrieves and decrypts the specified cookie.
		/// </summary>
		/// <param name="context">The current Context.</param>
		/// <param name="cookieName">The name of the Cookie to decrypt.</param>
		/// <returns>An cloned HttpCookie instance with the Value decrypted.</returns>
		public static HttpCookie Decrypt(HttpContext context, string cookieName)
		{
			HttpCookie encrypted = context.Request.Cookies[cookieName];
			if( encrypted == null ) return null;

			return Decrypt(encrypted);
		}
		
		/// <summary>
		/// Returns an encrypted cookie.
		/// </summary>
		/// <param name="source">The cookie to encrypt</param>
		/// <returns>An encrypted instance, cloned from the source.</returns>
		public static HttpCookie Encrypt(HttpCookie source)
		{
			try
			{
				byte[] data = System.Text.Encoding.Unicode.GetBytes(source.Value);
				byte[] encData = MachineKeyWrapper.EncryptOrDecryptData(true, data, null, 0, data.Length);

				HttpCookie encrypted = CloneCookie(source);
				encrypted.Value = MachineKeyWrapper.ByteArrayToHexString(encData, encData.Length);

				return encrypted;
			} 
			catch(Exception ex)
			{
				//repackage
				throw new HttpException("Unable to encrypt the cookie.",ex);
			}
		}
		/// <summary>
		/// Encrypts the specified cookie currently in the Response.
		/// </summary>
		/// <remarks>Note that this method actually changes the cookie currently in the Response.Cookies collection, 
		/// whereas the other Encrypt overload only returns a new instance, cloned from the cookie.</remarks>
		/// <param name="context"></param>
		/// <param name="cookieName"></param>
		/// <returns></returns>
		public static HttpCookie Encrypt(HttpContext context, string cookieName)
		{
			HttpCookie source = context.Response.Cookies[cookieName];
			HttpCookie encryptedCookie = Encrypt(source);
			context.Response.Cookies.Set(encryptedCookie);
			return encryptedCookie;
		}

		private static HttpCookie CloneCookie(HttpCookie source)
		{
			HttpCookie encrypted = new HttpCookie(source.Name);
			encrypted.Expires = source.Expires;
			encrypted.Path = source.Path;
			encrypted.Secure = source.Secure;
			encrypted.Domain = source.Domain;
			encrypted.Value = source.Value; //just being complete.
			return encrypted;
		}

	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions