我正在尝试使用Windows RT加密字符串。之前可以在ProtectData
命名空间中使用system.security
但在WinRT中不存在。我尝试使用以下代码,但它不起作用。
public static async Task<string> EncryptSting(string data)
{
DataProtectionProvider provider = new DataProtectionProvider();
IBuffer unprotectedData = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8);
//crashes here
IBuffer protectedData = await provider.ProtectAsync(unprotectedData);
return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, protectedData);
}
public static async Task<string> DecryptString(string data)
{
DataProtectionProvider provider = new DataProtectionProvider();
IBuffer inputData = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8);
//crashes here
IBuffer unprotectedData = await provider.UnprotectAsync(inputData);
return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, unprotectedData);
}
编辑:执行
提供的句柄无效。 (HRESULT异常:0x80090026)
并且在加密和解密时发生在第3行
答案 0 :(得分:3)
根据the documentation,您使用的构造函数只能用于解密,而不能用于加密:
用于解密操作的构造函数。在调用
UnprotectAsync
或UnprotectStreamAsync
方法之前使用此构造函数。
对于加密,您必须使用其他构造函数,该构造函数指定是否应为本地计算机,当前用户,特定用户等加密数据。
我不知道为什么它在您的情况下无法解密,但如果加密不起作用,我不确定您尝试解密的是什么...
答案 1 :(得分:1)
尝试执行以下操作:
public static async Task<string> EncryptSting(string data)
{
DataProtectionProvider provider = new DataProtectionProvider("LOCAL=user");
...
...
}
干杯!