Qt C ++ QString to convert QByteArray

I created an encryption / decryption program, when encrypting, I store the encrypted QByteArray array in a text file.

When I tried to decrypt, I received it and then put it in the decryption method, the problem is that I need a way to convert it to QByteArray without changing the format , otherwise it will not be decrypted correctly. I mean, if the file gave me an encrypted value of 1234, and I converted it to QByteArray by going to 1234.toLatin1() , it will change the value and the decryption will not work. Do you have some ideas?

My code is:

 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; 
+20
c ++ qt qstring qbytearray
source share
4 answers

I think you should use:

 QString::fromUtf8(const QByteArray &str) 

Or:

 QString::QString(const QByteArray &ba) 

to convert a QByteArray to a QString, and then write it to a file using QTextStream.
After that read the file from QTextStream, use:

 QString::toUtf8() 

to convert a QString to a QByteArray.

QString :: QString (const QByteArray & ba)

Creates a string initialized by byte array ba. This byte array is converted to Unicode using fromUtf8 () .


PS: Maybe it is better to use QFile :: write and QFile :: read.

+30
source share

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

+4
source share

Or just use b64 = data.toUtf8().toBase64();

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

0
source share

If I understand correctly, the text from the file is stored in the contents of QString. I think you can create a new QByteArray. Since the QByteArray constructor does not allow QString to be entered, I probably have to add a QString to an empty QByteArray.

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

I don't have much experience in the Qt library, but I hope this helps.

-2
source share

All Articles