簡體   English   中英

如何將MachineKey.Protect用於Cookie?

[英]How to use MachineKey.Protect for a cookie?

我想加密我在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?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM