AES Encryption Using Crypto++ .lib in Visual Studio C++

// code copy pasted from here https://www.cryptopp.com/w/images/b/bd/AES-CBC-Filter.zip

// crypto.cpp : This file contains the 'main' function. Program execution begins and ends there.

using CryptoPP::AutoSeededRandomPool;

using CryptoPP::Exception;

using CryptoPP::HexEncoder;

using CryptoPP::HexDecoder;

using CryptoPP::StringSink;

using CryptoPP::StringSource;

using CryptoPP::StreamTransformationFilter;

using CryptoPP::CBC_Mode;

int main(int argc, char* argv[])

AutoSeededRandomPool prng;

byte key[AES::DEFAULT_KEYLENGTH];

prng.GenerateBlock(key, sizeof(key));

prng.GenerateBlock(iv, sizeof(iv));

string plain = "CBC Mode Test";

string cipher, encoded, recovered;

/*********************************\

\*********************************/

StringSource(key, sizeof(key), true,

cout << "key: " << encoded << endl;

StringSource(iv, sizeof(iv), true,

cout << "iv: " << encoded << endl;

/*********************************\

\*********************************/

cout << "plain text: " << plain << endl;

CBC_Mode< AES >::Encryption e;

e.SetKeyWithIV(key, sizeof(key), iv);

// The StreamTransformationFilter removes

StringSource s(plain, true,

new StreamTransformationFilter(e,

) // StreamTransformationFilter

StreamTransformationFilter filter(e);

filter.Put((const byte*)plain.data(), plain.size());

const size_t ret = filter.MaxRetrievable();

filter.Get((byte*)cipher.data(), cipher.size());

catch (const CryptoPP::Exception& e)

cerr << e.what() << endl;

/*********************************\

\*********************************/

StringSource(cipher, true,

cout << "cipher text: " << encoded << endl;

/*********************************\

\*********************************/

CBC_Mode< AES >::Decryption d;

d.SetKeyWithIV(key, sizeof(key), iv);

// The StreamTransformationFilter removes

StringSource s(cipher, true,

new StreamTransformationFilter(d,

new StringSink(recovered)

) // StreamTransformationFilter

StreamTransformationFilter filter(d);

filter.Put((const byte*)cipher.data(), cipher.size());

const size_t ret = filter.MaxRetrievable();

filter.Get((byte*)recovered.data(), recovered.size());

cout << "recovered text: " << recovered << endl;

catch (const CryptoPP::Exception& e)

cerr << e.what() << endl;

/*********************************\

\*********************************/

Last updated