1

I am trying to decrypt a file encrypted using AES algorithm in CBC mode with PKCS padding. I found two classes in cryptopp library which can do it and not sure which one is better. Please suggest me which one is better.

One solution is to use instance of CBC_Mode< AES >::Decryption like this

using namespace std;
std::string getFstr(std::string fname)
{
    std::ifstream ifs(fname.c_str());
    std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );
    return content;
}

int main(int argc, char* argv[])
{
try
{
    std::string key_string = "576162746563205261696C7761792045";
    std::string enctext;
    byte no[] = {0x57,0x61,0x62,0x74,0x65,0x63,0x20,0x52,0x61,0x69,0x6C,0x77,0x61,0x79,0x20,0x45};

    byte noiv[AES::BLOCKSIZE];
    memset(noiv,0,sizeof(noiv));
    std::string out;
    enctext = getFstr(fileName);
    CBC_Mode< AES >::Decryption d;
    d.SetKeyWithIV(no, sizeof(no), noiv);
    StringSource s(enctext, true, new StreamTransformationFilter(d, new StringSink(out) ));
       return 0;
}
catch ( CryptoPP::Exception& e)
{
    std::cout << std::endl << e.what() << std::endl;
}
}

And another one is to use CryptoPP::AES::Decryption aesDecryption class as below

using namespace std;
std::string getFstr(std::string fname)
{
    std::ifstream ifs(fname.c_str());
    std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );
    return content;
}

int main(int argc, char* argv[])
{
try
{
    std::string key_string = "576162746563205261696C7761792045";
    std::string enctext;
    byte no[] = {0x57,0x61,0x62,0x74,0x65,0x63,0x20,0x52,0x61,0x69,0x6C,0x77,0x61,0x79,0x20,0x45};

    byte noiv[AES::BLOCKSIZE];
    memset(noiv,0,sizeof(noiv));
    std::string out;
    enctext = getFstr(fileName);    
   CryptoPP::AES::Decryption aesDecryption(no, sizeof(no));
   CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, noiv );
   CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( out ),CryptoPP::StreamTransformationFilter::PKCS_PADDING);
   stfDecryptor.Put( reinterpret_cast<const unsigned char*>( enctext.c_str() ), enctext.size() );
   stfDecryptor.MessageEnd();
return 0;
}
catch ( CryptoPP::Exception& e)
{
    std::cout << std::endl << e.what() << std::endl;
}
}

Thanks In Advance

user3494614
  • 603
  • 1
  • 7
  • 20
  • I'd use `CBC_Mode` for the simple reason that the Crypto++ wikipedia example [also seems to use it](https://www.cryptopp.com/wiki/CBC_mode) and you'd only have one object instance to handle. But that last observation can safely be concluded from the duplicate answer in my opinion. If you're missing anything, please indicate it in the question, in the comments below. – Maarten Bodewes Sep 26 '16 at 20:10

0 Answers0