SLa*_*aks 10
你可能不应该这样做.如果cookie是敏感的,则仅将其存储在服务器上.
如果你真的需要,有很多方法可以做到.首先,您需要将明文转换为字节数组,如下所示:
var plainBytes = Encoding.UTF8.GetBytes(plaintext);
Run Code Online (Sandbox Code Playgroud)
如果您确定您的纯文本永远不会使用Unicode,则可以使用Encoding.ASCII
; 这将导致更小的cookie).
然后,您将需要加密它.最简单的方法是使用DPAPI,就像这样.(首先,添加引用System.Security.dll
).请注意,这不适用于服务器场.
var encryptedBytes = ProtectedData.Protect(plainBytes, null, DataProtectionScope.CurrentUser);
Run Code Online (Sandbox Code Playgroud)
最后,您需要将其转换回文本,以便将其放入cookie中.这最好在Base64中完成,如下所示:
Response.AddCookie("MyEncryptedCookie", Convert.ToBase64String(encryptedBytes));
Run Code Online (Sandbox Code Playgroud)
要解密cookie,您需要撤消这些步骤,如下所示:
var encryptedBytes = Convert.FromBase64String(Request.Cookies["MyEncryptedCookie"].Value);
var decryptedBytes = ProtectedData.Unprotect(encryptedBytes , null, DataProtectionScope.CurrentUser);
var plaintext = Encoding.UTF8.GetString(decryptedBytes);
Run Code Online (Sandbox Code Playgroud)
请注意,即使对于小型明文,cookie也会非常大.
如果要在服务器场上使用它,可以使用AES; 看看System.Security.Cryptography.RijndaelManaged
.
归档时间: |
|
查看次数: |
6568 次 |
最近记录: |