Search code examples
qtencryptionaescrypto++

Having trouble decrypting a well-formed cipher text using Crypto++


Background

I've been struggling with decrypting an apparently well-formed cipher text for about a day. Assume we've got the following hex-encoded cipher text which contains exactly 160 characters thereby having 80 bytes.

QString c = "1BFAC407AF0D440A2D6176C0B5D125AA96088490299AC18C74623C0EF1BB1372E554FC4150A8066220E943697BE2491D8AE13AA036B298425AC510A8A917D59EBB69708B9040AB3A84C63043EAD4AB07";
QString k = CryptoUtils::hexEncode("abc");
QString p = CryptoUtils::decrypt(c, k);

qDebug() << p;

Provided we're using AES 256, AFAIK, the key must be of length 32 bytes and cipher text of a length of multiple of 16 bytes, which all these consditions are met regarding my snippet code.

Please note that I'm using SHA256 feeding with a pass phrase to generate a 32 bytes key. So, this ensures that all keys are of length 32 bytes.

Full source codes of those function can be found on my repo on GitHub (at branch Part1).


My Question

When I want to run this code, my app crashes. Here's the exception:

terminate called after throwing an instance of 'CryptoPP::InvalidCiphertext'
  what():  StreamTransformationFilter: invalid PKCS #7 block padding found
The program has unexpectedly finished.

I searched around about this problem and figured out it could be because of the trailing \0 once you encrypted the plain text. However, I couldn't just solve the problem. Please help me out, it's just driving me crazy.


Solution

  • The hexEncode function seems to misbehave:

    QString CryptoUtils::hexEncode(QString text)
    {
        byte *bytearray = (byte *) text.toLatin1().data();
        int length = text.toLatin1().length();
    
        return hexEncode(bytearray, length);
    }
    

    Should be replaced with:

    QString CryptoUtils::hexEncode(QString text)
    {
        byte *bytearray = (byte *) text.toStdString().data();
        int length = text.length();
    
        return hexEncode(bytearray, length);
    }