Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt C++ QString to QByteArray Conversion

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;
like image 748
James Avatar asked Jun 14 '16 03:06

James


People also ask

How do I write a QString file?

To write text, we can use operator<<(), which is overloaded to take a QTextStream on the left and various data types (including QString) on the right. In the following code, we open a new file with the given name and write a text into the file. Then, we read in the file back and print the content to our console.


2 Answers

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.

like image 67
Daniel Avatar answered Sep 21 '22 16:09

Daniel


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

like image 38
Ahmed Yossef Avatar answered Sep 18 '22 16:09

Ahmed Yossef