开发者

Encrypt cookies in ASP.NET

开发者 https://www.devze.com 2023-01-28 06:28 出处:网络
I would like to encrypt cookies in ASP.NET. I have followed the method in this article, but it has the drawback that is uses reflection on an internal method. This has caused it to be flagged in a co

I would like to encrypt cookies in ASP.NET.

I have followed the method in this article, but it has the drawback that is uses reflection on an internal method. This has caused it to be flagged in a code review -- it is not future-proof as the internal implementation may change.

Is there a method with identical functionality which doesn't require using encryption on internal methods?

I am using .NET Framework开发者_Python百科 3.5 SP1 (Assume I cannot change framework versions)


You don't need to roll your own any more.

.Net 4.5 has MachineKey.Protect() and MachineKey.Unprotect().

System.Web.Security.MachineKey

.Net 4.0 has MachineKey.Encode() and MachineKey.Decode(). You should just set the MachineKeyProtection to 'All'. These are now obsolete though and you should use the newer ones if you have 4.5.

Note if you try and use these in something like a console app instead of ASP.Net it seems to generate a new key with every app restart. I only checked it quickly but in ILSpy it looks like it generates its own defaults if the appropriate app.setting are missing.

I haven't been able to find a non-ASP.Net equivalent.


Why not just use the encryption found in System.Security.Cryptography to encrypt and decrypt the cookie name and value when it's sensitive? You can write some utility functions to manage it pretty easily. Example utility functions:

private static void SetEncryptedCookie(string name, string value)
{
    var encryptName = SomeEncryptionMethod(name);
    Response.Cookies[encryptName].Value = SomeEncryptionMethod(value);
    //set other cookie properties here, expiry &c.
    //Response.Cookies[encryptName].Expires = ...
}

private static string GetEncryptedCookie(string name)
{
    //you'll want some checks/exception handling around this
    return SomeDecryptionMethod(
               Response.Cookies[SomeDecryptionMethod(name)].Value);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消