Question

Is it explicitly allowed to use the same buffer for plaintext/ciphertext when performing AES encryption/decryption in CBC and ECB modes using Crypto++ (assuming the buffer size is sufficient to accomodate the encrypted data) as in the following code:

#include <cstdio>
#include <cassert>
#include "cryptopp\rsa.h"
#include "cryptopp\rijndael.h"
#include "cryptopp\modes.h"
int main()
{
    using namespace CryptoPP;
    byte key[32], iv[Rijndael::BLOCKSIZE];
    char testdata[] = "Crypto++ Test"; // any data can be here

    size_t buffer_size = (sizeof(testdata) + Rijndael::BLOCKSIZE) & ~(Rijndael::BLOCKSIZE - 1);
    byte* buffer = new byte[buffer_size];
    memcpy(buffer, testdata, sizeof(testdata));

    // encrypt data inplace
    CBC_Mode<Rijndael>::Encryption enc(key, sizeof(key), iv);
    MeterFilter meter(new ArraySink(buffer, buffer_size));
    ArraySource(buffer, sizeof(testdata), true, new StreamTransformationFilter(enc, new Redirector(meter), BlockPaddingSchemeDef::PKCS_PADDING));
    assert(meter.GetTotalBytes() == buffer_size);

    // decrypt data inplace
    CBC_Mode<Rijndael>::Decryption dec(key, sizeof(key), iv);
    MeterFilter meter2(new ArraySink(buffer, buffer_size));
    ArraySource(buffer, buffer_size, true, new StreamTransformationFilter(dec, new Redirector(meter2), BlockPaddingSchemeDef::PKCS_PADDING));
    assert(meter2.GetTotalBytes() == sizeof(testdata));

    printf("%s\n", static_cast<char*>(buffer));
    delete buffer;
}
Was it helpful?

Solution

In general, Crypto++ buffers can be the same or they can be distinct. I can't think of a situation where they are not allowed to be the same for in-place or in-situ processing of plain text or cipher text data. The only caveat is the buffer has to be larger enough for cipher text expansion.

You also have to be careful about overlap, but how you can get into trouble depends on the cipher. For example, AES in CBC_Mode operates on 16 byte blocks (the functions of interest are ProcessBlock, ProcessXorBlock, and friends). You can use an overlapped buffer as long as the difference between pointers is 17 bytes (or more). In the RSA case, you would likely need a difference of MaxPreImage size, which is based on the size of the modulus.

Finally, the old Crypto++ FAQ discusses it briefly as "in-line processing". See How do I use a block cipher in Crypto++ 4.x?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top