I am trying to encrypt a string with Windows RT. Before it was possible to use the ProtectData
in the system.security
namespace but that does not exist in WinRT. I tried to use the following code but it does not work.
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);
}
Edit: The execption is
The supplied handle is invalid. (Exception from HRESULT: 0x80090026)
and it occurs on the 3rd line when encrypting and decrypting
According to the documentation, the constructor you're using can only be used for decryption, not for encryption:
Constructor used for decryption operations. Use this constructor before calling the
UnprotectAsync
orUnprotectStreamAsync
methods.
For encryption, you must use the other constructor, which specifies if the data should be encrypted for the local machine, current user, specific user, etc.
I don't know why it doesn't work for decryption in your case, but if encryption doesn't work, I'm not sure what you're trying to decrypt...
Try to do the following:
public static async Task<string> EncryptSting(string data)
{
DataProtectionProvider provider = new DataProtectionProvider("LOCAL=user");
...
...
}
Cheers!
User contributions licensed under CC BY-SA 3.0