Geeks With Blogs
Amit's Blog Sharing Thoughts and Learning

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 .NET , C# , Asp.net , Security , Tips/Tricks , Cryptography | Back to top


Comments on this post: Secure Cookie

# Secure Cookie
Requesting Gravatar...
You've been kicked (a good thing) - Trackback from DotNetKicks.com
Left by DotNetKicks.com on Jan 18, 2007 1:30 PM

# re: Secure Cookie
Requesting Gravatar...
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
Left by Roger Strong on Jan 19, 2007 10:05 PM

# re: Secure Cookie
Requesting Gravatar...
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
Left by Tyrone on Jan 20, 2007 5:21 AM

# re: Secure Cookie
Requesting Gravatar...
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
Left by John S. on Jan 20, 2007 6:49 PM

# re: Secure Cookie
Requesting Gravatar...
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).
Left by Encoding Issues on Feb 02, 2007 11:58 PM

Your comment:
 (will show your gravatar)
 


Copyright © Kazi Manzur Rashid | Powered by: GeeksWithBlogs.net | Join free