因此,当我尝试在 WinRT ( Windows::Security::Cryptography
) 中使用新的加密命名空间时遇到了一个有趣的问题。也就是说,当我尝试使用CryptographicEngine::Encrypt()
orCryptographicEngine::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);
}
我仍然可以做一些愚蠢的事情(可能是),但不幸的是我没有看到它......有什么想法吗?
提前致谢!:)