Inplace AES CBC/ECB mode encrypting/decrypting using Crypto++

大憨熊 提交于 2019-12-23 19:34:08

问题


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

回答1:


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?



来源:https://stackoverflow.com/questions/16001214/inplace-aes-cbc-ecb-mode-encrypting-decrypting-using-crypto

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!