Click here to Skip to main content
15,894,646 members
Articles / Web Development / ASP.NET

HttpSecureCookie, A Way to Encrypt Cookies with ASP.NET 2.0

Rate me:
Please Sign up or sign in to vote.
4.90/5 (38 votes)
3 Apr 2006Ms-PL4 min read 524.5K   4.3K   112  
Discussing how to encode and tamper-proof text and cookies using the MachineKey, by using reflection
<%@ Page Language="C#" %>
<%@ Import Namespace="AdamTibi.Web.Security" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void btnStore_Click(object sender, EventArgs e) {
        HttpCookie cookie = new HttpCookie("UserName", "Terminator");
        cookie.Expires = DateTime.Now.AddDays(1);
        HttpCookie encodedCookie = HttpSecureCookie.Encode(cookie);
        Response.Cookies.Add(encodedCookie);
    }

    protected void btnDisplay_Click(object sender, EventArgs e) {
        HttpCookie cookie = Request.Cookies["UserName"];
        lblDisplayBefore.Text = cookie.Value;
        HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);
        lblDisplayAfter.Text = decodedCookie.Value;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Clicking this button will encode and store a cookie with Name=UserName and Value=Terminator<br />
        <asp:Button ID="btnStore" runat="server" OnClick="btnStore_Click" Text="Store" /><br />
        <br />
        Clicking this button will decode and display the content of the cookie havine Name=UserName<br />
        <asp:Button ID="btnDisplay" runat="server" OnClick="btnDisplay_Click" Text="Display" /><br />
        Before Decoding:
        <asp:Label ID="lblDisplayBefore" runat="server"></asp:Label><br />
        After Decoding:&nbsp; &nbsp;&nbsp;<asp:Label ID="lblDisplayAfter" runat="server"></asp:Label></div>
    </form>
</body>
</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Architect
United Kingdom United Kingdom
Passionate about refining software practices, promoting self-motivated teams and orchestrating agile projects.
Lives in London, UK and works as a .NET architect consultant in the City.

Blog AdamTibi.net.

Comments and Discussions