我试图用MachineKey加密和解密Id。
下面是调用加密和解密函数的代码:
var encryptedId = Encryption.Protect(profileId.ToString(), UserId);
var decryptedId = Encryption.UnProtect(encryptedId, UserId);以下是功能:
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);
}Protect方法的输入为15。这导致encryptedId变量包含以下字符串:6wOttbtJoVBV7PxhVWXGz4AQVYcuyHvTyJhAoPu4Okd2aKhhCGbKlK_T4q3GgirotfOZYZXke0pMdgwSmC5vxg2
为了对此进行加密,我将此字符串作为参数发送到UnProtect方法。解密的结果应该是15,而不是:1\05\0
我不明白为什么。我尝试在这个函数中只使用整数,但是我仍然有同样的问题。解密的输出不同。
发布于 2016-04-23 15:47:28
如果编码不匹配,则编码一个缓冲区,其中包含字符串的UTF-16 (Encoding.Unicode)表示形式(考虑到该字符串每个字符使用2个字节,这将交织\0 ),但您可以将其解码为UTF-8 (Encoding.UTF8)。在这两种方法中都需要保持一致。
https://stackoverflow.com/questions/36812592
复制相似问题