Click here to Skip to main content
Click here to Skip to main content

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

By , 3 Apr 2006
 

Introduction

I really have some good laughs when I tamper with cookies on my machine and watch the results when it is submitted back to the site. On the other hand, I don’t want any one to do the same to the cookies that I make!

Cookies, most of the times, shouldn’t be in plain text, at least, they should be tamper-proof! Revealing the content of your cookies might give curious and malicious people an idea about your application’s architecture, and that might help hacking it.

ASP.NET encodes and hashes its authorization ticket, making it secure and tamper-proof. However, the methods used to secure authorization cookies are inaccessible from outside the .NET framework libraries, so you can’t protect your own cookie using these methods; you need to protect it yourself using your own encryption key, encoding and hashing algorithms. HttpSecureCookie works around this by accessing the same methods ASP.NET uses for cookie authorization.

Of course, you shouldn’t save valuable information in your cookies, but if you have to, then this library is at your disposal.

Background

Before you start using this code, if you do not know what MachineKey is, I highly recommend checking this MSDN article: How To: Configure MachineKey in ASP.NET 2.0.

ASP.NET uses the System.Web.Security.CookieProtectionHelper internal class to decode and encode the content of a cookie before submitting it to the client. This class is based on the MachineKey. I wonder why Microsoft kept this class internal!?

To be able to access this internal class, I had to use reflection to be able to access the Decode and Encode methods of CookieProtectionHelper.

Eric Newton has a similar and good article on CP: Encrypting cookies to prevent tampering. However, that code is made for .NET 1.1 and it doesn't work with .NET 2.0 (but it does with some modifications); moreover, its resulting cipher text is in binary format versus being in encrypted format, and I don't know if this is a security risk. Also, I am accessing a higher level class System.Web.Security.CookieProtectionHelper than the one used by that article, System.Web.Configuration.MachineKey, to obtain the cryptography service, and that saved me time by not writing some low level code.

There is also another available method for encoding cookies, by using the FormsAuthenticationTicket and FormsAuthentication.Encrypt; for more information, check the section "Creating the Forms Authentication Cookie" on Explained: Forms Authentication in ASP.NET 2.0. However, I believe, the method mentioned in this article is more flexible.

Obtaining Reference to the CookieProtectionHelper Class via Reflection

To be able to access System.Web.Security.CookieProtectionHelper, I had to create a wrapper class CookieProtectionHelperWrapper which uses reflection to obtain a reference to the underlying methods and exposes the same methods as of the original class:

public static class CookieProtectionHelperWrapper {

    private static MethodInfo _encode;
    private static MethodInfo _decode;

    static CookieProtectionHelperWrapper() {
        // obtaining a reference to System.Web assembly
        Assembly systemWeb = typeof(HttpContext).Assembly;
        if (systemWeb == null) {
            throw new InvalidOperationException(
                "Unable to load System.Web.");
        }
        // obtaining a reference to the internal class CookieProtectionHelper
        Type cookieProtectionHelper = systemWeb.GetType(
                "System.Web.Security.CookieProtectionHelper");
        if (cookieProtectionHelper == null) {
            throw new InvalidOperationException(
                "Unable to get the internal class CookieProtectionHelper.");
        }
        // obtaining references to the methods of CookieProtectionHelper class
        _encode = cookieProtectionHelper.GetMethod(
                "Encode", BindingFlags.NonPublic | BindingFlags.Static);
        _decode = cookieProtectionHelper.GetMethod(
                "Decode", BindingFlags.NonPublic | BindingFlags.Static);

        if (_encode == null || _decode == null) {
            throw new InvalidOperationException(
                "Unable to get the methods to invoke.");
        }
    }

    public static string Encode(CookieProtection cookieProtection, 
                                byte[] buf, int count) {
        return (string)_encode.Invoke(null, 
                new object[] { cookieProtection, buf, count });
    }

    public static byte[] Decode(CookieProtection cookieProtection, 
                                string data) {
        return (byte[])_decode.Invoke(null, 
                new object[] { cookieProtection, data });
    }

}

MachineKeyCryptography: A Cryptography Class Based on MachineKey

MachineKeyCryptography is a static class that provides text ciphering and tamper-proofing services, it provides higher level access to CookieProtectionHelperWrapper. So, if you want to cipher any text based on the machine key, this class is the right one to use.

public static string Encode(string text, CookieProtection cookieProtection) {
    if (string.IsNullOrEmpty(text) || cookieProtection == CookieProtection.None) {
        return text;
    }
    byte[] buf = Encoding.UTF8.GetBytes(text);
    return CookieProtectionHelperWrapper.Encode(cookieProtection, buf, buf.Length); 
}

public static string Decode(string text, CookieProtection cookieProtection) {
    if (string.IsNullOrEmpty(text)) {
        return text;
    }
    byte[] buf;
    try {
        buf = CookieProtectionHelperWrapper.Decode(cookieProtection, text);
    }
    catch(Exception ex) {
        throw new InvalidCypherTextException(
            "Unable to decode the text", ex.InnerException);
    }
    if (buf == null || buf.Length == 0) {
        throw new InvalidCypherTextException(
            "Unable to decode the text");
    }
    return Encoding.UTF8.GetString(buf, 0, buf.Length);
}

HttpSecureCookie Class

This static class will handle the service of securing the content of a cookie. Also, it provides a service to clone a cookie. This class uses MachineKeyCryptography internally to provide crypting services:

public static class HttpSecureCookie {

    public static HttpCookie Encode(HttpCookie cookie) {
        return Encode(cookie, CookieProtection.All);
    }

    public static HttpCookie Encode(HttpCookie cookie, 
                  CookieProtection cookieProtection) {
        HttpCookie encodedCookie = CloneCookie(cookie);
        encodedCookie.Value = 
          MachineKeyCryptography.Encode(cookie.Value, cookieProtection);
        return encodedCookie;
    }

    public static HttpCookie Decode(HttpCookie cookie) {
        return Decode(cookie, CookieProtection.All);
    }

    public static HttpCookie Decode(HttpCookie cookie, 
                  CookieProtection cookieProtection) {
        HttpCookie decodedCookie = CloneCookie(cookie);
        decodedCookie.Value = 
          MachineKeyCryptography.Decode(cookie.Value, cookieProtection);
        return decodedCookie;
    }

    public static HttpCookie CloneCookie(HttpCookie cookie) {
        HttpCookie clonedCookie = new HttpCookie(cookie.Name, cookie.Value);
        clonedCookie.Domain = cookie.Domain;
        clonedCookie.Expires = cookie.Expires;
        clonedCookie.HttpOnly = cookie.HttpOnly;
        clonedCookie.Path = cookie.Path;
        clonedCookie.Secure = cookie.Secure;

        return clonedCookie;
    }
}

Using the Code

Using HttpSecureCookie is easy; for a complete demo, please check the sample application. To encode a cookie:

HttpCookie cookie = new HttpCookie("UserName", "Terminator");
cookie.Expires = DateTime.Now.AddDays(1);
HttpCookie encodedCookie = HttpSecureCookie.Encode(cookie);
Response.Cookies.Add(encodedCookie);

To decode an encoded cookie:

HttpCookie cookie = Request.Cookies["UserName"];
lblDisplayBefore.Text = cookie.Value;
HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);

To use HttpSecureCookie on a web farm, you need to set the correct MachineKey configuration in Web.Config. For more information, check the "Web Farm Deployment Considerations" section on How To: Configure MachineKey in ASP.NET 2.0. To generate a machine key, please check How to create keys by using Visual C# .NET for use in Forms authentication.

Limitations

This library uses reflection, so it might break with the next version of .NET. Also, it doesn't work with .NET 1.1.

Reflection might have some performance implication; however, I used an assembly that is already loaded, "System.Web.dll", and I am only using reflection once across the life time of the application, to gain extra performance.

Conclusion

If you don't want a sophisticated cookie encryption service, if you don't want to mind the encryption key, and if you don't want to create your own encryption algorithm, then this library is for you!

Comments and suggestions are welcome. Please vote if you like this article (or if you didn't).

History

  • 1 April 2006 - First version.

License

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

About the Author

Adam Tibi
Team Leader
United Kingdom United Kingdom
Member
Software Consultant, Lives in Guildford/Surrey, UK.
 
www.AdamTibi.net

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: Not working reliably in a web farm, even though machineKeys are syncedmemberfrankosaurus5 Dec '10 - 14:10 
GeneralWas working great - now throwing errorsmemberChuck Bevitt4 Nov '10 - 13:42 
GeneralRe: Was working great - now throwing errorsmembermoabi K15 May '11 - 17:55 
GeneralRe: Was working great - now throwing errorsmemberChuck Bevitt16 May '11 - 6:18 
GeneralRe: Was working great - now throwing errorsmemberdiego mesa tabares29 Sep '11 - 11:58 
GeneralI'm pretty sure I'm missing something, but...memberreinux1 Nov '10 - 21:26 
GeneralRe: I'm pretty sure I'm missing something, but...memberfrankosaurus5 Dec '10 - 14:06 
GeneralRe: I'm pretty sure I'm missing something, but...memberreinux5 Dec '10 - 14:46 
GeneralThanks for the propsmemberericnewton769 Jul '10 - 7:12 
GeneralMedium TrustmemberSpiff Dog1 Mar '10 - 10:40 
GeneralRe: Medium TrustmemberAdam Tibi2 Mar '10 - 0:12 
GeneralThanks for the insight Adam...I've actually implemented your code in my projectmemberZiad J.khan26 Nov '09 - 10:45 
GeneralRe: Thanks for the insight Adam...I've actually implemented your code in my projectmemberAdam Tibi30 Nov '09 - 2:20 
Thank you Ziad Smile | :)
 
Make it simple, as simple as possible, but not simpler.

Generalerror : padding is invalid...memberjamel197416 Sep '08 - 4:39 
GeneralRe: error : padding is invalid...memberAdam Tibi16 Sep '08 - 11:54 
GeneralRe: error : padding is invalid...memberjamel197416 Sep '08 - 21:03 
GeneralRe: error : padding is invalid...memberjamel197416 Sep '08 - 22:21 
GeneralInvalidCypherText.... no good.memberKurtPW29 Aug '08 - 13:31 
GeneralRe: InvalidCypherText.... no good.memberAdam Tibi31 Aug '08 - 11:47 
GeneralThanks Adammemberlehuuduc6 Aug '08 - 17:37 
GeneralRe: Thanks AdammemberAdam Tibi6 Aug '08 - 23:22 
GeneralDownload link error [modified]memberMarie-Christine Bechara6 May '08 - 2:52 
GeneralRe: Download link errormemberAdam Tibi8 May '08 - 23:05 
GeneralPadding is invalid and cannot be removed.memberSurjit Singh23 Apr '08 - 0:00 
GeneralRe: Padding is invalid and cannot be removed.memberAdam Tibi24 Apr '08 - 22:32 
QuestionClarificationmemberstixoffire1 Apr '08 - 22:57 
Generalthank youmemberRob van der Veer25 Feb '08 - 4:38 
GeneralRe: thank youmemberAdam Tibi25 Feb '08 - 22:04 
QuestionHow do you delete the cookie?memberSimon Deshaies10 Dec '07 - 6:11 
QuestionInvalidCypherTextException can't find?memberdianlongliu27 Nov '07 - 14:18 
AnswerRe: InvalidCypherTextException can't find?memberAdam Tibi27 Nov '07 - 23:45 
GeneralRe: InvalidCypherTextException can't find?memberdianlongliu28 Nov '07 - 3:30 
GeneralRe: InvalidCypherTextException can't find?memberAdam Tibi28 Nov '07 - 23:03 
GeneralRe: InvalidCypherTextException can't find?memberdianlongliu29 Nov '07 - 14:55 
GeneralRe: InvalidCypherTextException can't find?memberdianlongliu29 Nov '07 - 15:00 
GeneralRe: InvalidCypherTextException can't find?memberAdam Tibi29 Nov '07 - 23:39 
GeneralRe: InvalidCypherTextException can't find?memberdianlongliu30 Nov '07 - 3:10 
QuestionPadding exceptionmemberDaberElay9 Sep '07 - 22:07 
AnswerRe: Padding exceptionmemberAdam Tibi9 Sep '07 - 22:30 
AnswerRe: Padding exceptionmemberBoxcarwilli15 Sep '07 - 19:37 
AnswerRe: Padding exceptionmemberrsmith6661 Oct '07 - 15:33 
Generalthank umemberMember #396127727 Mar '07 - 1:03 
GeneralRe: thank umemberAdam Tibi28 Mar '07 - 9:19 
GeneralGreat articlememberazam's22 Feb '07 - 18:07 
GeneralRe: Great articlememberAdam Tibi22 Feb '07 - 22:39 
GeneralWell done Adam!membernighthawk132 Jul '06 - 10:53 
GeneralGREAT!memberKevin I13 Apr '06 - 18:04 
GeneralCool articlememberMoustafa Banbouk11 Apr '06 - 17:58 
GeneralRe: Cool articlememberAdam Tibi12 Apr '06 - 0:11 
GeneralGood onememberVasudevan Deepak Kumar4 Apr '06 - 4:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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