使用 Crypto++(假设缓冲区大小足以容纳加密数据)在 CBC 和 ECB 模式下执行 AES 加密/解密时,是否明确允许对明文/密文使用相同的缓冲区,如以下代码所示:
#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;
}