How to use MachineKey.Protect for a cookie?

后端 未结 1 1705
眼角桃花
眼角桃花 2021-02-05 04:49

I want to encrypt the ID that I am using in a cookie. I am using ASP.NET 4.5 so I want to use MachineKey.Protect to do it.

Code

    public s         


        
相关标签:
1条回答
  • 2021-02-05 05:13

    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);
    }
    
    0 讨论(0)
提交回复
热议问题