How to set up encryption for cookies

So normally I use Sessions for maintaining user state. I store various bits of information about the user such as userid and other identifiers that allow me to present the user with a custom view that is relevant to him/her.

This works okay, but I'd like to change it up a little so I'm looking at using encrypted cookies.

I have in my solution a class called ortund.Hashing where I keep methods and functions for password encryption/decryption and generating keys, etc.

I figured I'd use System.Security.Cryptography as per the accepted answer here which contains the following code:

private static void SetEncryptedCookie(string name, string value) { var encryptName = SomeEncryptionMethod(name); Response.Cookies[encryptName].Value = SomeEncryptionMethod(value); //set other cookie properties here, expiry &c. //Response.Cookies[encryptName].Expires = ... } private static string GetEncryptedCookie(string name) { //you'll want some checks/exception handling around this return SomeDecryptionMethod( Response.Cookies[SomeDecryptionMethod(name)].Value); } 

The only problem with this is that my Hashing class doesn't exist in a web application that can use Response.Cookies.

This has me stumped… Can anyone suggest how I can proceed?

Thanks in advance!

by ortund via /r/csharp

Leave a Reply