Search code examples
c#encryptionuwpaesencryption-symmetric

C# UWP CryptographicEngine.Encrypt() returns null


I trying to encrypt input bytes[] to AES, but final encryption buffer is null.

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();
}

Debugger show local variables as (Name, Value, Type):

+       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>

Where is my fault?


Solution

  • I even cannot run your code snippet successfully on my side, exception System.ArgumentException: 'Value does not fall within the expected range. will be thrown when CreateSymmetricKey(key). Your key seems to be the wrong length, the key length should be a certain number of bits long based on the security you need. (256 bits for AES is common).

    In additional, CBC algorithms require an initialization vector, you could assign a random number for the vector. More details please reference Symmetric keys .

    Please try to fix your issue and implement the encrypt feature by following the official sample or this example.