Search code examples
c#cookiesasp.net-4.5

How to use MachineKey.Protect for a cookie?


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

When I use the following test data:

Protect():

Input: 775119337

Output: (Cookie) "HyV7ShLrb61cm9HWoHl2lUJtGMlMxLn60q27xwl7Ae1wpv31p7sJqfRDD8TMoSR8n8PPN1K7k7LsrjqWH6A-P17OblK3MApsDQRQLa8xj9A1"

UnProtect():

Output: "NwA3ADUAMQAxADkAMwAzADcA0"

The output isn't correct, of course, it should be the original ID I Input.

How do I get decrypt the cookie using MachineKey.UnProtect()?


Solution

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