0

So, I am using a cookie to store some basic data. All works fine. Now, I want to encrypt the cookie data. I am using TripleDES encryption (192). This works fine but one of the requirements is to encrypt the entire data in one big long string - later on when reading, will have to manually parse out the values after decrypting - that's ok.

The odd problem is that, when I encrypt the name value and then set the encrypted value to it, next time I read it on a DIFFERENT request (i.e button click), it does not find the key/name! I look in the object visualizer and see that the name indeed is slightly different than what I had originally assigned it:

// save

var cookie = new HttpCookie("MyCookie");
var encryptedName = MySecurityHelper.TripleDES.Encrypt("UserInfo");
var encryptedData = MySecurityHelper.TripleDES.Encrypt("Id:1[]Name:Joe"); // [] is the delimiter
cookie[encryptedName] = encryptedData;
Response.Cookies.Add(cookie);

// read

var cookie = Request.Cookies["MyCookie"];
var encryptedName = MySecurityHelper.TripleDES.Encrypt("UserInfo");
var decryptedData = MySecurityHelper.TripleDES.Decrypt(cookie[encryptedName]);

any ideas why?

so when saving, the cookie name value could be: FzgGr1=

but then after when interrogating the cookie object, its FzgGr1

any ideas why it would be different on the subsequent request? Totally weird and unexplainable.

Ahmed ilyas
  • 5,722
  • 8
  • 44
  • 72

1 Answers1

3

Browsers send cookies to server along with request headers. And there are several reserved characters('=',';','&'), which should be avoided in cookie name or value.

W3C Specification

Try this,

cookie[System.Web.HttpUtility.UrlEncode(encryptedName)] = System.Web.HttpUtility.UrlEncode(encryptedData);

Screenshot of this page's request header Screenshot of this page's request header

EDIT : Allowed characters in cookies

Community
  • 1
  • 1
Ajeesh M
  • 2,092
  • 1
  • 14
  • 18