Windows.Security.Cryptography.Core.CryptographicEngine.Encrypt()抛出InvalidCastException

时间:2016-10-14 03:20:46

标签: c# cryptography uwp hololens

我将一些加密代码移植到UWP for HoloLens。 AFAIK,我已经根据UWP要求完美地实现了它,但是我从以下代码中得到了一个神秘的InvalidCastException:

public override byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
IBuffer dataBuffer = WindowsRuntimeBuffer.Create(clearData, 0, clearData.Length, clearData.Length);
IBuffer keyBuffer = WindowsRuntimeBuffer.Create(Key, 0, Key.Length, Key.Length);
IBuffer ivBuffer = WindowsRuntimeBuffer.Create(IV, 0, IV.Length, IV.Length);

string strAlgName = KeyDerivationAlgorithmNames.Pbkdf2Sha256;

// Open the specified algorithm.
KeyDerivationAlgorithmProvider objAlgProv = KeyDerivationAlgorithmProvider.OpenAlgorithm(strAlgName);

// Create a key by using the passed buffer.
CryptographicKey key = objAlgProv.CreateKey(keyBuffer);

IBuffer encryptedData = CryptographicEngine.Encrypt(key, dataBuffer, ivBuffer); // throws System.InvalidCastException
return (byte[])encryptedData.ToArray();

我不确定问题是什么。我已经验证了传递给CryptographicEngine.Encrypt的所有参数的类型是正确的类型。我之前在字节数组上尝试过AsBuffer扩展方法;我切换到WindowsRuntimeBuffer.Create认为可能会做的伎俩,但它没有任何区别。 dataBuffer和ivBuffer都是WindowsRuntimeBuffer类型,它实现了IBuffer,两者的长度是8的倍数(分别为32和16)。我尝试过铸造IBuffer;那是行不通的。我甚至尝试生成3个随机的IBuffers,全部是长度为32,以确定这是否至少有效;它没有用。这是一个错误,还是我错过了一些非常明显的东西?此外,InvalidCastException是完全通用的,只能从我自己的应用程序中获取StackTrace,它绝对没有告诉我。

FWIW,这里是整个堆栈跟踪:

   at Windows.Security.Cryptography.Core.CryptographicEngine.Encrypt(CryptographicKey key, IBuffer data, IBuffer iv)
   at dk.UWP.Crypto.UWPSimpleEncryption.Encrypt(Byte[] clearData, Byte[] Key, Byte[] IV)
   at dk.UWP.Crypto.UWPSimpleEncryption.Encrypt(String clearText, String Password)
   at dk.Crypto.SimpleEncryption.Encrypt(String clearText, String Password)
   at bbtb.Scene.BBTBInitialization.<DeferSplashForInitialization>d__19.MoveNext()
   at UnityEngine.SetupCoroutine.InvokeMoveNext(IEnumerator enumerator, IntPtr returnValueAddress)
   at UnityEngine.SetupCoroutine.$Invoke1InvokeMoveNext(Int64 instance, Int64* args)
   at UnityEngine.Internal.$MethodUtility.InvokeMethod(Int64 instance, Int64* args, IntPtr method)

1 个答案:

答案 0 :(得分:0)

看起来,无论出于何种原因,MSDN提供的示例KeyDerivationAlgorithmProvider和KeyDerivationAlgorithmNames都不起作用。如果您改为使用SymmetricAlgorithmNames和SymmetricAlgorithmProvider,它似乎工作正常。我不确定这是不是设计;如果是这样,它完全没有记录。如果我发现它,我会发布更多信息。

相关问题