WinRT CryptographicEngine ::加密/解密抛出InvalidArgumentException

时间:2012-10-12 04:38:01

标签: c++ encryption windows-runtime

因此,当我尝试在WinRT(Windows::Security::Cryptography)中使用新的加密命名空间时,我遇到了一个有趣的问题。也就是说,当我尝试使用CryptographicEngine::Encrypt()CryptographicEngine::Decrypt()方法时,他们会抛出InvalidArgumentException。我不是这个领域的专业人士,但我觉得我已经把它缩小到一个相当基本的场景,我仍然失败了:

//------------------------------------------------------------------------------
// TestEncryptDecrypt
// Simple test that encrypts a string, then decrypts it and compares the result.
void TestEncryptDecrypt()
{
    // Select asymmetric algorithm
    Platform::String^ strAlgorithm = Windows::Security::Cryptography::Core::AsymmetricAlgorithmNames::RsaOaepSha512;
    Windows::Security::Cryptography::Core::AsymmetricKeyAlgorithmProvider^ spAlgorithm = Windows::Security::Cryptography::Core::AsymmetricKeyAlgorithmProvider::OpenAlgorithm(strAlgorithm);

    // Create public/private keys
    unsigned int nKeySize = 512;
    Windows::Security::Cryptography::Core::CryptographicKey^ spKeyPair = spAlgorithm->CreateKeyPair(nKeySize);

    // Message to encrypt/decrypt
    Platform::String^ strMessage = L"Test Message";
    Windows::Storage::Streams::IBuffer^ spMessageBuffer = Windows::Security::Cryptography::CryptographicBuffer::ConvertStringToBinary(strMessage, Windows::Security::Cryptography::BinaryStringEncoding::Utf8);

    // Encrypt the data
    // *** InvalidArgumentException throw here ***
    Windows::Storage::Streams::IBuffer^ spEncryptedBuffer = Windows::Security::Cryptography::Core::CryptographicEngine::Encrypt(spKeyPair, spMessageBuffer, nullptr /*Initialization vector not used with asymmetric algorithms.*/);

    // Decrypt the data
    Windows::Storage::Streams::IBuffer^ spUnencryptedBuffer = Windows::Security::Cryptography::Core::CryptographicEngine::Decrypt(spKeyPair, spEncryptedBuffer, nullptr /*Initialization vector not used with asymmetric algorithms.*/);

    // Retrieve the original message
    Platform::String^ strUnencryptedMessage = Windows::Security::Cryptography::CryptographicBuffer::ConvertBinaryToString(Windows::Security::Cryptography::BinaryStringEncoding::Utf8, spUnencryptedBuffer);
    Assert(strUnencryptedMessage == strMessage);
}

我仍然可以做一些愚蠢的事情(也许可能是),但不幸的是我没有看到它...任何想法?

提前致谢! :)

1 个答案:

答案 0 :(得分:2)

像往常一样,我在发布后半小时偶然发现答案......:)

事实证明,RSA_OAEP_SHA512不支持我使用的密钥大小。你需要使用一个更大的密钥(我实际上在切换到512之前尝试了1024,但似乎也太小了)。使用2048或4096的密钥大小可以正常工作。

无论如何,我通过玩WinRT Crypto样本来解决这个问题,该样本可以在http://code.msdn.microsoft.com/windowsapps/CryptoWinRT-54ff3d9f找到。它也抛出异常,但附近有一些错误处理代码,表明在捕获相当无用的异常后发生了什么。样本编写得很好,所以如果你遇到类似的问题,我建议你查一下。

另外,我发现在创建密钥时不会抛出异常,这有点令人讨厌,因为获取InvalidArgumentException足够神秘,而不会把它扔进一个有趣的地方。似乎在密钥创建过程中可能会抛出它,因为此时已经选择了算法。

无论如何,问题已经解决了,希望这篇文章可以帮助其他人!