Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 513
David Avatar asked May 17 '13 21:05

David


People also ask

What is Machinekey used for?

Use the Machine Key feature page to configure hashing and encryption settings used for application services, such as view state, Forms authentication, membership and roles, and anonymous identification. Machine keys are also used to verify out-of-process session state identification.

Is Machinekey protect secure?

The Protect method performs the appropriate operation and securely protects the data. Ciphertext data produced by this method can only be deciphered by the Unprotect method.


1 Answers

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); } 
like image 173
SLaks Avatar answered Sep 22 '22 21:09

SLaks