在ASP.NET中encryptioncookie

我想在ASP.NET中encryptioncookie。

我已经遵循了本文中的方法 ,但是它的缺点是在内部方法上使用了reflection。 这已经导致它在代码审查中被标记 – 这是不是未来的certificate,因为内部实现可能会改变。

有没有一种方法具有相同的function,不需要在内部方法上使用encryption?

我正在使用.NET Framework 3.5 SP1(假设我不能更改框架版本)

为什么不使用System.Security.Cryptography中的encryption来encryption和解密cookie名称和值? 你可以写一些实用的function来pipe理它很容易。 示例效用函数:

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

你不需要再滚动自己的。

.Net 4.5有MachineKey.Protect()MachineKey.Unprotect()

System.Web.Security.MachineKey

.Net 4.0有MachineKey.Encode()MachineKey.Decode() 。 您应该将MachineKeyProtection设置为“全部”。 这些现在已经过时了,如果你有4.5,你应该使用新的。

请注意,如果您尝试使用控制台应用程序而不是ASP.Net,它似乎会在每次重新启动应用程序时生成一个新的密钥。 我只检查它快速,但在ILSpy它看起来像它产生自己的默认值,如果适当的app.setting丢失。

我还没有find一个非ASP.Net等价物。