You should probably not do this. If the cookie is confidential, save it only on the server.
If you really need to, there are several ways to do this. First, you will need to convert the plaintext to an array of bytes, for example:
var plainBytes = Encoding.UTF8.GetBytes(plaintext);
If you are sure that your plaintext will never use Unicode, you can use Encoding.ASCII ; this will decrease the cookie).
Then you will need to encrypt it. The easiest way to do this is to use DPAPI like this. (First, add the link to System.Security.dll ). Note that this will not work on the server farm.
var encryptedBytes = ProtectedData.Protect(plainBytes, null, DataProtectionScope.CurrentUser);
Finally, you need to convert it to text so that you can put it in a cookie. This is best done in Base64, for example:
Response.AddCookie("MyEncryptedCookie", Convert.ToBase64String(encryptedBytes));
To decrypt a cookie, you need to undo these steps, for example:
var encryptedBytes = Convert.FromBase64String(Request.Cookies["MyEncryptedCookie"].Value); var decryptedBytes = ProtectedData.Unprotect(encryptedBytes , null, DataProtectionScope.CurrentUser); var plaintext = Encoding.UTF8.GetString(decryptedBytes);
Please 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; take a look at System.Security.Cryptography.RijndaelManaged .