Search code examples
c#asp.net-mvcsecurityhttpcookie

safe and secure HTTPCookie storage in ASP.NET MVC C# application


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;
        }

    }
}

Solution

  • You can use the Protect and Unprotect methods to encrypt cookies. Note that both bytes have the same key value. Data encrypted with Protect can only be decrypted with Unprotect.

    encrypted method

    public string encryptedCookie(string value)
    {
        var cookieText = Encoding.UTF8.GetBytes(value);
        var encryptedValue = Convert.ToBase64String(MachineKey.Protect(cookieText, "ProtectCookie"));
        return encryptedValue;
    }
          
    

    decrypted method

    public string decryptedCookie(string value)
    {
        var bytes = Convert.FromBase64String(value);
        var output = MachineKey.Unprotect(bytes, "ProtectCookie");
        string result = Encoding.UTF8.GetString(output);
        return result;
    }
    

    Instead of "ProtectCookie", you can use your unique key.