asp.net - 将 System.Web.Security.MachineKey.Encode 替换为 System.Web.Security.MachineKey.Protect

标签 asp.net encryption decode encode

我刚刚将一个项目从 .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 已被弃用,取而代之的是这些新的 ProtectUnprotect 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/

相关文章:

java - 将字节缓冲区转换为字符串在 Java 中不起作用

google-apps-script - 实用程序 base64Encode 与 base64Decode 方法

c# - 如何以编程方式检查 System.webServer/Security/requestFiltering 部分是否存在?

security - 如果您不进行金融交易,是否值得使用 https?

ASP.NET 和 Web Tools 2012.2 引用 LESS 文件

c++ - 加密/解密期间 Crypto++ 显式销毁?

c# - Rijndael:C++加密,C#解密

java - 如何在不完全解码的情况下计算 png 文件的颜色?

c# - 如何使用 Javascript 或 JQuery 获取页面内容

asp.net - 如何设置高度自动 CSS 属性?