Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I encrypt a cookie content in a simple way in C# 3.0?

How can I encrypt a cookie in a direct and simple way?

Thanks!!

like image 686
André Miranda Avatar asked Jul 07 '09 15:07

André Miranda


1 Answers

You probably shouldn't be doing this. If the cookie is sensitive, store it only on the server.

If you really need to, there are a number of ways to do it. First, you will need to convert the plaintext to a byte array, like this:

var plainBytes = Encoding.UTF8.GetBytes(plaintext);

If you're sure that your plaintext will never use Unicode, you can use Encoding.ASCII instead; this will result in a smaller cookie).

Then, you will need to encrypt it. The easiest way to do that is to use DPAPI, like this. (First, add a reference to System.Security.dll). Note that this will not work on a server farm.

var encryptedBytes = ProtectedData.Protect(plainBytes, null, DataProtectionScope.CurrentUser);

Finally, you need to convert it back to text so you can put it in the cookie. This is best done in Base64, like this:

Response.AddCookie("MyEncryptedCookie", Convert.ToBase64String(encryptedBytes));

To decrypt the cookie, you'll need to reverse these steps, like this:

var encryptedBytes = Convert.FromBase64String(Request.Cookies["MyEncryptedCookie"].Value);
var decryptedBytes = ProtectedData.Unprotect(encryptedBytes , null, DataProtectionScope.CurrentUser);
var plaintext = Encoding.UTF8.GetString(decryptedBytes);

Note that the cookie will be very large, even for small plaintexts.

If you want to use this on a server farm, you can use AES; look at System.Security.Cryptography.RijndaelManaged.

like image 64
SLaks Avatar answered Nov 07 '22 00:11

SLaks