38

I have created an encrypt/decrypt program, when encrypting I store the encrypted QByteArray in a text file.

When trying to decrypt I retrieved it and then put it into the decryption method, the problem is that I need a way to convert it to QByteArray without changing the format, otherwise it will not decrypt properly. What I mean is if the file gave me an encrypted value of 1234 and I converted that to QByteArray by going 1234.toLatin1() it changes the value and the decryption does not work. Any suggestions?

My Code:

QFile file(filename);
    QString encrypted;
    QString content;

    if (file.open(QIODevice::ReadOnly)) {
        QTextStream stream( &file );
        content = stream.readAll();
    }

    encrypted = content.replace("\n", "");

    qDebug() << encrypted; // Returns correct encrypted value

    QByteArray a;
    a += encrypted;

    qDebug() << "2 " + a; // Returns different value than previous qDebug()

    QByteArray decrypted = crypto.Decrypt(a, key);
    return decrypted;
AAEM
  • 1,837
  • 2
  • 18
  • 26
James
  • 773
  • 1
  • 6
  • 15

5 Answers5

46

I guess you should use:

QString::fromUtf8(const QByteArray &str)

Or:

QString::QString(const QByteArray &ba)

to convert QByteArray to QString, then write it into file by QTextStream.
After that, read file by QTextStream, use:

QString::toUtf8()

to convert QString to QByteArray.

QString::QString(const QByteArray &ba)

Constructs a string initialized with the byte array ba. The given byte array is converted to Unicode using fromUtf8().


P.S: Maybe use QFile::write and QFile::read is a better way.

AAEM
  • 1,837
  • 2
  • 18
  • 26
Daniel
  • 573
  • 4
  • 11
  • I'd rather use QString::fromUtf8 directly instead of implicit QString<->QByteArray conversions, to make the conversion between plain data and unicode explicit and to state the assumed encoding of the data. – Frank Osterfeld Jun 14 '16 at 05:42
  • 4
    This is the opposite direction from what the title says, for people looking up a similar question... – Christopher Pisz Jun 30 '20 at 19:24
10

try using toUtf8() .. it works fine with me

Ahmed Yossef
  • 365
  • 3
  • 8
  • 1
    `toUtf8()` is probably a better option because it can handle all of the characters that `QString` can. https://doc.qt.io/qt-5/qstring.html#toUtf8 – Soren Stoutner Apr 20 '22 at 21:57
0

If I understand correctly, the text from the file is store in the QString content. I think you could create a new QByteArray. Because the constructor of a QByteArray does not allow a QString as input, I will probably have to append the QString to the empty QByteArray.

//After if:  
QByteArray tempContent();
tempContent.append(content);
QByteArray decrypted = crypto.Decrypt(tempContent, key);

I do not have much experience in the Qt library, but I hope this helps.

  • This did convert succesfully but after testing it returned `?\x01?YJ?l?p3&?\x11\x1Bv/?X??c?U?~{?a??` and it should be `?\u0001?YJ?l?p3&?\u0011\u001Bv/?X??c?U?~{?a??` Why might the value be changing? since I used qDebug() and `content` before creating the `QByteArray` is the correct value – James Jun 14 '16 at 04:04
  • I've edited my post and added my whole function if it helps – James Jun 14 '16 at 04:09
  • No idea why this has downvotes, it's perfectly fine. – Zimano Jan 23 '18 at 15:05
  • This does an ASCII or Latin1 encoding conversion implicitly so unicode won't work with it. Hence the reason Qt allows this constructor to be disabled. – wheredidthatnamecomefrom Nov 08 '22 at 14:42
0

Or simply go with b64 = data.toUtf8().toBase64();

First convert it to QByteArray with the toUtf8() and then immediately convert it to toBase64()

Skonitsa
  • 96
  • 1
  • 9
0

There's a simple way :

   QByteArray ba;
   QString qs = "String";
   ba += qs;

More hard way:

QByteArray ba;
QDataStream in(&ba, QIODevice::WriteOnly);
in << QString("String");

Extreme way, for people who want to use QBuffer:

#include <QDebug>
#include <QBuffer>
#include <QDataStream>
#include <QIODevice>
#include <QByteArray>
#include <QString>
#include <qcoreapplication.h>

int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);
   QByteArray byteArray;
   QBuffer buffer(&byteArray);
   buffer.open(QIODevice::ReadWrite);
   QDataStream in( &buffer );
   in << QString("String");
   buffer.close();

   for (int i = 0; i < byteArray.length(); ++i) {
      printf("%c - %x\n", byteArray.at(i), byteArray.at(i));
   }

   printf("\n");
   

return a.exec();
}

Who run last code can ask me where does the null byte come from?

QDataStream serializes the QString as a little-endian. 4 bytes are read to create the 32-bit length value, followed by the string itself in UTF-16. This string length in UTF-16 is 12 bytes, so the first three bytes in QByteArray will be zero.

There is often a problem with reading the QByteArray in qDebug () The recording is fine. Don't forget to remove QT_NO_CAST_FROM_BYTEARRAY in your .pro file, if it has