Search code examples
c++qtcrypto++

Decrypted image is not same as original image


I just started working on cryptopp library. I have a image buffer and i want to encrypt with some key and then decrypt later but facing issue, decrypted and original images are not same. I am not sure weather issue in encryption or not could some one help me out of this.

using qt creator

Code:

AutoSeededRandomPool prng;

SecByteBlock key(AES::DEFAULT_KEYLENGTH);
prng.GenerateBlock( key, key.size() );

byte ctr[ AES::BLOCKSIZE ];
prng.GenerateBlock( ctr, sizeof(ctr) );

string cipher, encoded, recovered;

QFile file("original.png");
if(!file.open(QIODevice::ReadOnly)){
    cout << "could not open the file"<< endl;
}

QByteArray buffer = file.readAll();

qDebug()<<"buffer length"<<buffer.length();

file.close();

try
{
    CTR_Mode< AES >::Encryption e;
    e.SetKeyWithIV( (byte*)key.data(), key.size(), ctr );

    StringSource ss1( buffer, true,
                      new StreamTransformationFilter( e,
                                                      new StringSink( cipher )
                                                      )
                      );

}
catch( CryptoPP::Exception& e )
{
    cerr << e.what() << endl;
    exit(1);
}

qDebug()<<"cipher length "<<cipher.length();

try
{
    CTR_Mode< AES >::Decryption d;
    d.SetKeyWithIV( (byte*)key.data(), key.size(), ctr );
    StringSource ss3( cipher, true,
                      new StreamTransformationFilter( d,
                                                      new StringSink( recovered )
                                                      )
                      );

}
catch( CryptoPP::Exception& e )
{
    cerr << e.what() << endl;
    exit(1);
}

qDebug()<<"recovered length "<<recovered.length();
QFile ouput("recovered.png");
if(ouput.open(QIODevice::WriteOnly)){
    ouput.write(recovered.data(), recovered.size());
    ouput.close();
}

response:

buffer length 538770
cipher length  8
recovered length  8

why my cipher length is 8 only.


Solution

  • I found the issue with QByteArray buffer. i just converted to std::string its working.

    QByteArray buffer = file.readAll();
    
    // string
    std::string stdString(buffer.data(), buffer.length());
    
    //used stdString instead of buffer in pipeline
    StringSource ss1(stdString, true,
                                  new StreamTransformationFilter( e,
                                                                  new StringSink( cipher )
                                                                  )
                                  );