如何在C#3.0中以简单的方式加密Cookie内容? [英] How can I encrypt a cookie content in a simple way in C# 3.0?

查看:112
本文介绍了如何在C#3.0中以简单的方式加密Cookie内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以直接而简单的方式加密Cookie?

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

谢谢!!

推荐答案

你可能不应该这样做。如果cookie是敏感的,只存储在服务器上。

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);

如果您确定您的纯文本永远不会使用Unicode,您可以使用 Encoding.ASCII 这将导致更小的cookie)。

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

然后,您需要加密它。最简单的方法是使用DPAPI,像这样。 (首先,添加对 System.Security.dll 的引用)。注意,这不会在服务器场上工作。

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);

最后,您需要将其转换回文本,以便将其放入cookie。这最好在Base64中完成,像这样:

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));






要解密Cookie,请按照以下步骤操作:


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);

请注意,即使对于小的明文,cookie也会非常大。

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

如果要在服务器场上使用此选项,可以使用AES;请查看 System.Security。 Cryptography.RijndaelManaged

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

这篇关于如何在C#3.0中以简单的方式加密Cookie内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆