Simple way to encrypt data in winrt

2

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

encryption
windows-runtime
data-protection
asked on Stack Overflow Jun 8, 2014 by sidy3d • edited Jun 9, 2014 by sidy3d

2 Answers

3

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 or UnprotectStreamAsync 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...

answered on Stack Overflow Jun 16, 2014 by Thomas Levesque
1

Try to do the following:

public static async Task<string> EncryptSting(string data)
{
    DataProtectionProvider provider = new DataProtectionProvider("LOCAL=user");
    ...
    ...
}

Cheers!

answered on Stack Overflow Apr 11, 2016 by Sam

User contributions licensed under CC BY-SA 3.0