How to use MachineKey.Protect for a cookie?

[亡魂溺海] 提交于 2019-12-03 01:18:35
SLaks

decodedValue is the bytes you passed to MachineKey.Protect().
This is not UrlTokenEncoded; it's Unicode-encoded bytes.

You need to call Encoding.Unicode.GetString().


From the 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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!