【问题标题】:How to use MachineKey.Protect for a cookie?如何将 MachineKey.Protect 用于 cookie?
【发布时间】:2013-05-13 03:47:00
【问题描述】:

我想加密我在 cookie 中使用的 ID。我正在使用 ASP.NET 4.5,所以我想使用 MachineKey.Protect 来做。

代码

    public static string Protect(string text, string purpose)
    {
        if (string.IsNullOrEmpty(text))
            return string.Empty;
        
        byte[] stream = Encoding.Unicode.GetBytes(text);
        byte[] encodedValue = MachineKey.Protect(stream, purpose);
        return HttpServerUtility.UrlTokenEncode(encodedValue);
    }

    public static string Unprotect(string text, string purpose)
    {
        if (string.IsNullOrEmpty(text))
            return string.Empty;

        byte[] stream = HttpServerUtility.UrlTokenDecode(text);
        byte[] decodedValue = MachineKey.Unprotect(stream, purpose);
        return HttpServerUtility.UrlTokenEncode(decodedValue);
    }

当我使用以下测试数据时:

Protect():

输入:775119337

输出:(Cookie)“HyV7ShLrb61cm9HWoHl2lUJtGMlMxLn60q27xwl7Ae1wpv31p7sJqfRDD8TMoSR8n8PPN1K7k7LsrjqWH6A-P17OblK3MApsDQRQLa8xj9A1”

UnProtect():

输出:“NwA3ADUAMQAxADkAMwAzADcA0”

输出不正确,当然应该是我输入的原始ID。

如何使用MachineKey.UnProtect() 解密 cookie?

【问题讨论】:

  • 对于较短的字符串,您应该使用 UTF8。

标签: c# cookies asp.net-4.5


【解决方案1】:

decodedValue 是您传递给MachineKey.Protect() 的字节。
这不是 UrlTokenEncoded;它是 Unicode 编码的字节。

您需要致电Encoding.Unicode.GetString()


来自 OP:

public static string Protect(string text, string purpose)
{
    if (string.IsNullOrEmpty(text))
        return null;

    byte[] stream = Encoding.UTF8.GetBytes(text);
    byte[] encodedValue = MachineKey.Protect(stream, purpose);
    return HttpServerUtility.UrlTokenEncode(encodedValue);
}

public static string Unprotect(string text, string purpose)
{
    if (string.IsNullOrEmpty(text))
        return null;

    byte[] stream = HttpServerUtility.UrlTokenDecode(text);
    byte[] decodedValue = MachineKey.Unprotect(stream, purpose);
    return Encoding.UTF8.GetString(decodedValue);
}

【讨论】:

  • 感谢您的解释。它帮助我解决了不断抛出的 Base64 错误!还有很多与此相关的其他问题和答案,我希望包括您的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-16
  • 2018-10-06
  • 2016-05-21
  • 1970-01-01
  • 2016-09-30
  • 2021-09-01
相关资源
最近更新 更多