我正在将一些加密代码移植到用于 HoloLens 的 UWP。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 都是实现 IBuffer 的 WindowsRuntimeBuffer 类型,并且都是 8 的倍数(分别为 32 和 16)。我尝试转换为 IBuffer;那没有用。我什至尝试生成 3 个长度为 32 的随机 IBuffer,看看这是否至少可以工作;它不起作用。这是一个错误,还是我错过了一些非常明显的东西?此外,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)