25

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()?

Community
  • 1
  • 1
David
  • 2,063
  • 3
  • 24
  • 31

1 Answers1

46

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);
}
George Stocker
  • 55,025
  • 29
  • 167
  • 231
SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
  • Thanks for this explanation. It helped me with Base64 errors that kept on getting thrown! There are a lot of other questions and answers related to this that I wish included your explanation. – Marcel Gruber Nov 30 '16 at 19:44