Amit's Blog

Sharing Thoughts and Learning

  Home  |   Contact  |   Syndication    |   Login
  43 Posts | 1 Stories | 153 Comments | 14 Trackbacks

News

About Me?
Read it in
Blog Statistics
Proud Member of

Archives

Post Categories

Articles

Book Review

I Visit.

OpenSource Project(s)

This my second post of almost same topic asp.net lacking. This time it is Cookie. Still Asp.net has the lacking of creating encrypted cookie. Here is another handy class which generates encrypted cookie.

Usage:

//Writing Cookie
SecureCookie.Set(Response, "Key1", "Value1", DateTime.Now.AddDays(1));
SecureCookie.Set(Response, "Key1", "Value1"); //Overloaded
//Reading Cookie
string key1Value = SecureCookie.Get(Request, "Key1");

SecureCookie:

using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Diagnostics;
using System.Security.Cryptography;


public sealed class SecureCookie
{
//Rijndael Key size is 256 bit or 32 byte, Can also be mentioned in web.config instead of hardcoding
private static readonly byte[] Key = new byte[] {45, 236, 171, 7, 85, 6, 41, 34, 216, 14, 78, 156, 78, 3, 103, 154, 9, 150, 65, 54, 226, 95, 68, 79, 159, 36, 246, 57, 177, 107, 116, 8};

[DebuggerStepThrough()]
public static void Set(HttpResponse response,
string key,
string value,
DateTime expire)
{
HttpCookie cookie = new HttpCookie(HttpUtility.UrlEncode(Encrypt(key)), HttpUtility.UrlEncode(Encrypt(value)));

if ((expire != DateTime.MinValue) && (expire != DateTime.MaxValue))
{
cookie.Expires = expire;
}

response.Cookies.Set(cookie);
}

[DebuggerStepThrough()]
public static void Set(HttpResponse response,
string key,
string value)
{
Set(response, key, value, DateTime.MaxValue);
}

[DebuggerStepThrough()]
public static string Get(HttpRequest request, string key)
{
HttpCookie cookie = request.Cookies[HttpUtility.UrlEncode(Encrypt(key))];

if (cookie == null)
{
return null;
}

if ((cookie.Value == null) || (cookie.Value.Length == 0))
{
return null;
}

string value = HttpUtility.UrlDecode(cookie.Value);

return Decrypt(value);
}

[DebuggerStepThrough()]
private static string Encrypt(string plain)
{
if ((plain == null) || (plain.Length == 0))
{
return null;
}

using(SymmetricAlgorithm crypto = CreateCrypto())
{
return System.Convert.ToBase64String(Read(crypto.CreateEncryptor(), Encoding.ASCII.GetBytes(plain)));
}
}

[DebuggerStepThrough()]
private static string Decrypt(string cipher)
{
if ((cipher == null) || (cipher.Length == 0))
{
return null;
}

using(SymmetricAlgorithm crypto = CreateCrypto())
{
return Encoding.ASCII.GetString(Read(crypto.CreateDecryptor(), System.Convert.FromBase64String(cipher)));
}
}

[DebuggerStepThrough()]
private static SymmetricAlgorithm CreateCrypto()
{
//Using Rijndael as it is much more secure among the others
SymmetricAlgorithm crypto = new RijndaelManaged();

crypto.Key = Key;
crypto.IV = new byte[crypto.IV.Length];

return crypto;
}

[DebuggerStepThrough()]
private static byte[] Read(ICryptoTransform transformer,
byte[] data)
{
using(MemoryStream ms = new MemoryStream())
{
using(CryptoStream cs = new CryptoStream(ms, transformer, CryptoStreamMode.Write))
{
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();

return ms.ToArray();
}
}
}
}

kick it on DotNetKicks.com

posted on Thursday, January 18, 2007 11:20 PM

Feedback

# Secure Cookie 1/18/2007 1:30 PM DotNetKicks.com
You've been kicked (a good thing) - Trackback from DotNetKicks.com

# re: Secure Cookie 1/19/2007 10:05 PM Roger Strong
ASP.Net 2 can create encryted cookies.

Dim sRole As String = User.Roles
Dim ticket As New FormsAuthenticationTicket(1, User.User_ID, DateTime.Now, DateTime.Now.AddMinutes(30), True, sUserData, FormsAuthentication.FormsCookiePath)
Dim hash As String = FormsAuthentication.Encrypt(ticket)
Dim cookie As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, hash)
Response.Cookies.Add(cookie)

Roger Strong
rstrong@yetmans.mb.ca


# re: Secure Cookie 1/20/2007 5:21 AM Tyrone
You probably should take a look at making changes in the web.config for forms authentication.

See this resource: http://quickstarts.asp.net/QuickStartv20/aspnet/doc/security/formsauth.aspx


# re: Secure Cookie 1/20/2007 6:49 PM John S.
I've had a lot of success with the HttpSecureCookie class over on codeproject (it seems that I can't submit the link) codeproject/aspnet/HttpSecureCookie.asp

# re: Secure Cookie 2/2/2007 11:58 PM Encoding Issues
I've been using this class to store an object serialized as xml, but had an issue with the "ñ" spanish character (It gets transformed to "?"). The solution I found is to use Encoding.UTF8 instead of Encoding.ASCII. Is there a particular reason to use Encoding.ASCII? (I do not understand much about encodings).

Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: 
Please add 7 and 8 and type the answer here: