Wednesday, 4 February 2015

Encrypt Decrypt Cookies in Asp.net

In this article, I am explain how to Encrypt and Decrypt cookie values. 

Design Source Code:

<div>
            <asp:TextBox ID="txtvalue" runat="server" placeholder="Enter Some Text" Width="250">
            </asp:TextBox><br />
            <asp:Label runat="server" ID="lblmsg" ForeColor="Green" Font-Bold="true"></asp:Label><br />
            <asp:Button ID="btnEncrypt"
                runat="server" Text="Encrypt" OnClick="btnEncrypt_Click" />&nbsp;&nbsp;
            <asp:Button ID="btnDecrypt" runat="server" Text="Decrypt" OnClick="btnDecrypt_Click" Style="height: 26px" />
        </div>

Code Behind:
Using namespaces:
using System.Text;
using System.Web.Security;

protected void btnEncrypt_Click(object sender, EventArgs e)
{
byte[] bCookieText = Encoding.UTF8.GetBytes(txtvalue.Text);
string sEncryptedValue = Convert.ToBase64String(MachineKey.Protect(bCookieText, "ProtectCookie"));

HttpCookie oHttpCookie = new HttpCookie("NameOfCookie", sEncryptedValue);

//---- Set expiry time of cookie.
oHttpCookie.Expires.AddDays(5);
Response.Cookies.Add(oHttpCookie);
lblmsg.Text = sEncryptedValue;
}
protected void btnDecrypt_Click(object sender, EventArgs e)
{
byte[] bytes = Convert.FromBase64String(Request.Cookies["NameOfCookie"].Value);
byte[] bOutput = MachineKey.Unprotect(bytes, "ProtectCookie");
string sOutput = Encoding.UTF8.GetString(bOutput);
lblmsg.Text = sOutput;

}

For Asp.Net 4.0

Encryption:
var plaintextBytes = Encoding.UTF8.GetBytes("Jitendra Gangwar");
var encryptedValue = MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);
Response.Write(encryptedValue.ToString());

Decryption:
var decryptedBytes = MachineKey.Decode(encryptedValue, MachineKeyProtection.All);
var decryptedValue = Encoding.UTF8.GetString(decryptedBytes);
Response.Write(decryptedValue);

OutPut:




Download Here


No comments:

Post a Comment