我刚刚将一个项目从 .NET 4.0 升级到 .NET 4.5.1,这产生了以下警告:
Public Shared Function Encode(data() As Byte, protectionOption As System.Web.Security.MachineKeyProtection) As String' is obsolete: 'This method is obsolete and is only provided for compatibility with existing code. It is recommended that new code use the Protect and Unprotect methods instead.'
我有很多值漂浮在使用 Encode 加密的 cookie 和电子邮件中。如果我要用保护/取消保护替换编码/解码,我仍然需要能够解密那些旧的加密值。是否可以取消对使用 Encode 加密的值的保护?
最佳答案
在 .NET 4.0 中,您可以使用 MachineKey API 来保护/取消保护数据,如下所示:
string Protect(byte[] data)
{
if (data == null || data.Length == 0) return null;
return MachineKey.Encode(data, MachineKeyProtection.All);
}
byte[] Unprotect(string value)
{
if (String.IsNullOrWhiteSpace(value)) return null;
return MachineKey.Decode(value, MachineKeyProtection.All);
}
MachineKey.Encode
接受一个 byte[]
来保护并返回一个字符串。第二个参数是一个枚举,指示您是否需要加密、验证或两者兼而有之。我通常建议两者(MachineKeyProtection.All
)。然后,可以使用返回的字符串作为 cookie 值或查询字符串值传回客户端,而无需担心查看或篡改。 MachineKey.Decode
只是简单地反转该过程。
这是 4.5 的用法:
string Protect(byte[] data)
{
if (data == null || data.Length == 0) return null;
var value = MachineKey.Protect(data, "");
return Convert.ToBase64String(value);
}
byte[] Unprotect(string value)
{
if (String.IsNullOrWhiteSpace(value)) return null;
var bytes = Convert.FromBase64String(value);
return MachineKey.Unprotect(bytes, "");
}
在 4.5 中,旧 API 已被弃用,取而代之的是这些新的 Protect
和 Unprotect
API。新的 API 不再接 protected 级别(它们现在总是加密和 MAC [这很好]),而是接受一个名为 目的
的新参数。此目的参数旨在充当验证机制。如果我们使用特定于用户的值(正如我们上面使用 GetMachineKeyPurpose
帮助程序所做的那样),那么我们将验证该值只能不受同一用户的保护。这是 4.5 中的一个很好的补充。
关于asp.net - 将 System.Web.Security.MachineKey.Encode 替换为 System.Web.Security.MachineKey.Protect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33674059/