How can I encrypt cookie content in an easy way in C # 3.0?

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

Thanks!!

+6
cookies encryption
source share
3 answers

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 .

+10
source share

The easiest way is not to encrypt it! Just use the cookie id (plus salt) to view the values โ€‹โ€‹(content) on the server.

+2
source share

The safest way to do this is to use the ASP.Net session state instead of cookies. Since session state is never sent to the client, you have nothing to worry about.

-2
source share

All Articles