Encrypt Decrypt Cookies in asp .net

In this asp .net tutorial we will learn how to Encrypt and Decrypt cookie values. Cookies are small text files to hold values within browser. As cookies are stored in a plain text file it is very easy to read and modify content of the cookies. However you can encrypt and decrypt cookies to provide some security.  For this tutorial we will use MachineKey.Protect” and “MachineKey.Unrotect” methods for encryption and decryption. These are the inbuilt methods used to Encrypt and Decrypt data in asp .net.

 
Encrypt Cookies:
 
        //--- Add following namespaces
        //using System.Text;
        //using System.Web.Security;

        var cookieText = Encoding.UTF8.GetBytes("Text for Cookie");
        var encryptedValue = Convert.ToBase64String(MachineKey.Protect(cookieText, "ProtectCookie"));

        //--- Create cookie object and pass name of the cookie and value to be stored.
        HttpCookie cookieObject = new HttpCookie("NameOfCookie", encryptedValue);

        //---- Set expiry time of cookie.
        cookieObject.Expires.AddDays(5);

        //---- Add cookie to cookie collection.
        Response.Cookies.Add(cookieObject);
 
Decrypt Cookies:
 
        var bytes = Convert.FromBase64String(Request.Cookies["NameOfCookie"].Value);
        var output = MachineKey.Unprotect(bytes, "ProtectCookie");
        string result = Encoding.UTF8.GetString(output);
 
From the above example we can see how to read and write cookies in asp .net and how to encrypt and decrypt cookies in asp .net. We have successfully encrypted and Decrypted cookies values in above example but still it is advised not to use cookies for sensitive data and data which is required for critical calculations. As users are not able to read the encrypted data but they still able to tamper the cookie content. 
 
Some other examples of cookies:
 

 

cookies-encrypt-decrypt-example-in-asp-net-codingfusion

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice