Im trying to encrypt and decrypt an identifier using MachineKey.
Here is my code that calls the encryption and decryption functions:
var encryptedId = Encryption.Protect(profileId.ToString(), UserId);
var decryptedId = Encryption.UnProtect(encryptedId, UserId);
Here are the functions:
public static string Protect(string text, string purpose)
{
if(string.IsNullOrEmpty(text))
{
return string.Empty;
}
byte[] stream = Encoding.Unicode.GetBytes(text);
byte[] encodedValues = MachineKey.Protect(stream, purpose);
return HttpServerUtility.UrlTokenEncode(encodedValues);
}
public static string UnProtect(string text, string purpose)
{
if(string.IsNullOrEmpty(text))
{
return string.Empty;
}
byte[] stream = HttpServerUtility.UrlTokenDecode(text);
byte[] decodedValues = MachineKey.Unprotect(stream, purpose);
return Encoding.UTF8.GetString(decodedValues);
}
The method input Protectis 15. This causes the encryptedId variable to contain the following line:6wOttbtJoVBV7PxhVWXGz4AQVYcuyHvTyJhAoPu4Okd2aKhhCGbKlK_T4q3GgirotfOZYZXke0pMdgwSmC5vxg2
To encrypt this, I send this string as a parameter to the method UnProtect. The result of decryption should be 15, but instead:1\05\0
I do not understand why. Who can help me?
I have a trid to use only integers in this function, but I still have the same problem. Decryption output is different.
Bryan source
share