I'm using the below class to handle cookies and use them to store/read values in my ASP.NET MVC application (such as shopping cart items, etc.)
1.I want to know if values are stored without any security in the browser and anyone can look inside its content (using the below implementation)? I checked that values are stored as some hexadecimal values but I doubt that any specific encryption/security exists in this implementation.
2.How can I modify this class to store cookie values as encrypted information?
using System;
using System.Web;
namespace My.Application.Sample
{
public class CookieStore
{
public static void SetCookie(string key, string value)
{
SetCookie(key, value, TimeSpan.FromDays(14));
}
public static void SetCookie(string key, string value, TimeSpan expires)
{
string encodedValue = HttpUtility.UrlEncode(value);
HttpCookie encodedCookie = new HttpCookie(key, encodedValue);
if (HttpContext.Current.Request.Cookies[key] != null)
{
var cookieOld = HttpContext.Current.Request.Cookies[key];
cookieOld.Expires = DateTime.Now.Add(expires);
cookieOld.Value = encodedCookie.Value;
HttpContext.Current.Response.Cookies.Add(cookieOld);
}
else
{
encodedCookie.Expires = DateTime.Now.Add(expires);
HttpContext.Current.Response.Cookies.Add(encodedCookie);
}
}
/// <summary>
/// Return value stored in a cookie by defined key, if not found returns empty string
/// </summary>
/// <param name="key"></param>
/// <returns> never returns null! :) </returns>
public static string GetCookie(string key)
{
string value = string.Empty;
try
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
//if (cookie != null)
//{
// // For security purpose, we need to encrypt the value.
// HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);
// value = decodedCookie.Value;
//}
if (cookie != null)
{
string encodedValue = cookie.Value;
value = HttpUtility.UrlDecode(encodedValue);
}
}
catch (Exception)
{
}
return value;
}
}
}