在winrt中加密数据的简单方法

时间:2014-06-08 22:56:26

标签: encryption windows-runtime data-protection

我正在尝试使用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行

2 个答案:

答案 0 :(得分:3)

根据the documentation,您使用的构造函数只能用于解密,而不能用于加密:

  

用于解密操作的构造函数。在调用UnprotectAsyncUnprotectStreamAsync方法之前使用此构造函数。

对于加密,您必须使用其他构造函数,该构造函数指定是否应为本地计算机,当前用户,特定用户等加密数据。

我不知道为什么它在您的情况下无法解密,但如果加密不起作用,我不确定您尝试解密的是什么...

答案 1 :(得分:1)

尝试执行以下操作:

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

干杯!