How can I encrypt a cookie in a direct and simple way?
Thanks!!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
If you’re sure that your plaintext will never use Unicode, you can use
Encoding.ASCIIinstead; 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.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:
To decrypt the cookie, you’ll need to reverse these steps, like this:
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.