C#UWP CryptographicEngine.Encrypt()返回null

时间:2018-04-23 16:15:36

标签: c# encryption uwp aes encryption-symmetric

我尝试将输入字节[]加密为AES,但最终加密缓冲区为空。

private byte[] Encrypt(byte[] data)
{
    byte[] secretKey = new byte[] { 1, 2, 3 };

    IBuffer key = Convert.FromBase64String(Convert.ToBase64String(secretKey.ToArray()).ToString()).AsBuffer();
    Debug.WriteLine(key.Length);
    SymmetricKeyAlgorithmProvider algorithmProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc);
    CryptographicKey cryptographicKey = algorithmProvider.CreateSymmetricKey(key);
    IBuffer bufferEncrypt = CryptographicEngine.Encrypt(cryptographicKey, data.AsBuffer(), null);

    return bufferEncrypt.ToArray();
}

调试器将局部变量显示为(名称,值,类型):

+       this    {Project.Auth}  Project.Auth
+       data    {byte[15]}  byte[]
    bufferEncrypt   null    Windows.Storage.Streams.IBuffer
+       cryptographicKey    {Windows.Security.Cryptography.Core.CryptographicKey}   Windows.Security.Cryptography.Core.CryptographicKey
+       key {System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBuffer}    Windows.Storage.Streams.IBuffer {System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBuffer}
+       algorithmProvider   {Windows.Security.Cryptography.Core.SymmetricKeyAlgorithmProvider}  Windows.Security.Cryptography.Core.SymmetricKeyAlgorithmProvider
+       SecretKey   Count = 16  System.Collections.Generic.List<byte>

我的错在哪里?

1 个答案:

答案 0 :(得分:0)

我甚至无法成功运行您的代码段,System.ArgumentException: 'Value does not fall within the expected range.时会抛出异常CreateSymmetricKey(key)。您的密钥似乎是错误的长度,密钥长度应该是一个特定的位长,具体取决于您需要的安全性。 (AES通常为256位。)

另外,CBC算法需要初始化向量,您可以为向量分配随机数。更多详情请参阅Symmetric keys

请尝试按照official samplethis example修复您的问题并实施加密功能。