C++ – AES, 128 and 256 Invalid Key Length

aesaes-gcmccrypto++encryption

I am trying to encrypt a text using Crypto++. It worked well last time when using AES CTR, but now when using CBC or GCM the max key length I can use is 32 bits??

The code that handles the encryption:

string xAESPlain, xAESCipher;
AutoSeededRandomPool xRng;

byte xAESKey[128]; // Doesnt Work has to be 32 or 16
byte xAESIv[128];

xRng.GenerateBlock(xAESKey, sizeof(xAESKey));
xRng.GenerateBlock(xAESIv, sizeof(xAESIv));

CBC_Mode< AES >::Encryption E;
E.SetKeyWithIV(xAESKey, sizeof(xAESKey), xAESIv);

StringSource ss(xAESPlain, true,
    new StreamTransformationFilter(E,
        new StringSink(xAESCipher)
    )
);

When running this Crypto++ throws an Exception:

terminate called after throwing an instance of 'CryptoPP::InvalidKeyLength'
  what():  AES/CBC: 128 is not a valid key length

Note that the same thing happens when using the example.zip provided in the Wiki(and changing the key length to 256 or 128)

Any ideas why the Exception is being thrown?

Best Answer

Bytes are usually octets (8 bits). AES is specified for 128-bit block size or 16 bytes which is also the size of the IV. AES key sizes may be 128-bit, 192-bit or 256-bit or 16 byte, 24 byte or 32 byte respectively. They can't be different from those. So use this for AES-256:

byte xAESKey[32];
byte xAESIv[16];

This should have nothing to do with the mode of operation.