Hi everyone! How can I encrypt a cookie in a direct and simple way?
Thanks!!
Hi everyone! How can I encrypt a cookie in a direct and simple way?
Thanks!!
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
.
The most secure way to do this is to use ASP.Net session state instead of cookies. Since session state is never sent to the client, you will have nothing to worry about.