Address: Http://www.codeproject.com/Tips/872826/Encrypt-Decrypt-Cookies-in-ASP-NET
Source code: Http://files.cnblogs.com/files/yplong/ShanuBasicCSharpOOPConceptV1.4.zip
Brief introduction:
In this topic, I'll show you how to encrypt and decrypt the value of a cookie. A cookie is a text file that stores values on the browser side. stored in a simple text file as a cookie, it is easy to read and modify the contents of cookies.
However, you can encrypt and decrypt cookies to achieve a certain degree of security. In this article we will use"MachineKey.Protect
andMachineKey.Unprotect
"Two methods to encrypt and decrypt.
machinekey.protect ()  
and MachineKey.Unprotect()
theis applied in the asp.net4.5. These two methods require 2 parameters, the first parameter is the byte form of the content file to be encrypted and decrypted, and the second parameter is the purpose. The purpose is like a key, which can be a value of type string. We need to protect and protect the value with the same goal value.
Source Design:
1<div>2<asp:textbox id="Txtvalue"runat="Server" 3Placeholder="Enter Some Text"Width=" -">4</asp:textbox><br/>5<asp:label runat="Server"Id="lblmsg"Forecolor="Green" 6Font-bold="true"></asp:label><br/>7<asp:button id="Btnencrypt"8runat="Server"text="Encrypt" 9onclick="Btnencrypt_click"/>Ten<asp:button id="Btndecrypt"runat="Server"text="Decrypt" Oneonclick="Btndecrypt_click"style="height:26px"/> A</div>
The actual operation of the code:
Use a namespace:
1 //using System.Text;2 //using System.Web.Security;3 4 protected voidBtnencrypt_click (Objectsender, EventArgs e)5 {6 varCookietext =Encoding.UTF8.GetBytes (txtvalue. Text);7 varEncryptedvalue = convert.tobase64string (Machinekey.protect (Cookietext,"Protectcookie"));8 9 //---Create cookie object and pass name of the cookie and value to is stored.TenHttpCookie Cookieobject =NewHttpCookie ("Nameofcookie", encryptedvalue); One A //----Set Expiry time of the cookie. -CookieObject.Expires.AddDays (5); - the //----ADD cookie to cookie collection. - Response.Cookies.Add (cookieobject); -Lblmsg. Text =Encryptedvalue; - } + protected voidBtndecrypt_click (Objectsender, EventArgs e) - { + varbytes = Convert.frombase64string (request.cookies["Nameofcookie"]. Value); A varOutput = Machinekey.unprotect (Bytes,"Protectcookie"); at stringresult =Encoding.UTF8.GetString (output); -Lblmsg. Text =result; -}
In ASP. NET 4.0:
Encryption:
1 var plaintextbytes = Encoding.UTF8.GetBytes ("jitendra gangwar"); 2 var encryptedvalue = Machinekey.encode (plaintextbytes, machinekeyprotection.all); 3 Response.Write (encryptedvalue.tostring ());
Decrypt:
1 var decryptedbytes = Machinekey.decode (encryptedvalue, machinekeyprotection.all); 2 var decryptedvalue = Encoding.UTF8.GetString (decryptedbytes); 3 Response.Write (Decryptedvalue);
Output:
How to encrypt and decrypt cookies in ASP.