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.
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()
?
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With