Search code examples
c++qtencryptionqbytearray

Qt C++ How to save QByteArray for encrypted text to a file, then read and format back as a QByteArray


I have a very simple encrypt/decrypt program. After the encryption my program returns the encrypted text as a QByteArray which I then save into a text file. When retrieving the ByteArray from the file for decryption I'm not sure if it is formatting correctly or if the file is adding some kind of extra characters like a \n

Here is my encrypt/decrypt functions:

void Handler::updatePMEF(QString format) {

    SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023));
    QString result = crypto.encryptToByteArray(format);

    QFile file("C:/test.txt");
    if ( file.open(QIODevice::ReadWrite) ) {
        QTextStream stream( &file );
        stream << result << endl;
    }
}

QString Handler::openPMEF() {
    QByteArray encrypted;

    QFile file("C:/test.txt");
    if ( file.open(QIODevice::ReadOnly) ) {
         encrypted = file.readAll();
    }

    SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023));
    QString decrypted = crypto.decryptToByteArray(encrypted);

    return decrypted;
}

After calling openPMEF() the debugger returns nothing so I assume something is going wrong.

Before I tried doing QByteArray = encrypted in hopes that it would convert and the debugger returned:

Decrypyted: ????\u00153C?????qW\f????\u00153\u0019????\u00153\u001C????\u0006 \u001C?????2\u0014\u001C????\f*v?????\u00153'?????\u0004\"~?D?\u0005?\u00153(???? \u0006\u001Cf???\u00153I?????dB2??\u00153\u001C????\u00153l?????-\u000B\u001C?????\u00153I?????\u00153\u001C????\u0018>\u001Cf???\u00153(?????jLa????\u00153\u0006?????\u001D;)????DbK????~X\u0010Ö???\u0001'\u001B?????rTl?????\u0005#Z????X~Q?????F`G???²\u001A<B???? \u0006G?????F`r????? \u0006

Solution

  • This is most likely because you used QTextStream upon writting. For instance, this one will most likely stop on the first OES (\0), while your crypted data may contain many.

    You should use a function writting directly a QByteArray.

    Try writting using this:

    file.write( result.toAscii() );
    

    I'm not sure what encoding you should use (that could also explain it fails in your code, if reading/writting enciding is different. You may try all available: result.toLatin1(), result.toLocal8Bit(), result.toUtf8(). Hopefully, one will work as expected.

    By the way, maybe QString is not adapted to store your data in the first place. Can't you adapt SimpleCrypt::encryptToByteArray to return a QByteArray?

    Edit: As discussed offline, final solution was to modify SimpleCrypt::encryptToByteArray to return a QByteArray instead of a QString (QString is meant to store strings not byte arrays)