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