Click here to Skip to main content
12,395,252 members (57,038 online)
Click here to Skip to main content


111 bookmarked

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

, 3 Apr 2006 Ms-PL
Discussing how to encode and tamper-proof text and cookies using the MachineKey, by using reflection.
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Assembly Name="AdamTibi.Web.Security" %>
<%@ Import Namespace="AdamTibi.Web.Security" %>

<head runat="server">

    HttpCookie cookie = new HttpCookie("UserName", "Terminator");
    cookie.Expires = DateTime.Now.AddYears(30);
    // Encoding the cookie then tamering it before decoding.
    HttpCookie encodedCookie = HttpSecureCookie.Encode(cookie, CookieProtection.Validation);
    Response.Write("Cookie value after encode with CookieProtection.Validation:<br />" + encodedCookie.Value + "<br /><br />");

    // Tampering
    encodedCookie.Value = encodedCookie.Value.Replace("X", "Y");

    HttpCookie decodedCookie;
    try {
        decodedCookie = HttpSecureCookie.Decode(encodedCookie, CookieProtection.Validation);
    catch (InvalidCypherTextException ex) {
        Response.Write("unable to decode the cookie: " + ex.Message);
    // This line will never be reached because the cookie is tampered with.



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.


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


About the Author

Adam Tibi
United Kingdom United Kingdom
Passionate about refining software practices, promoting self-motivated teams and orchestrating agile projects that hit the deadline.
Lives in London, UK and works as a .NET architect consultant in the City.

Need a pro service to help your organisation? Contact me via my website

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 3 Apr 2006
Article Copyright 2006 by Adam Tibi
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid