Problemas con la conversión entre QString y QByteArray

I have a strange issue converting QString to QByteArray:

qDebug()<<"content to encryp:\n"<<content<<"\n";
QString pwHash = generalSettings.password;
QByteArray secretKey;
QString clearText(content);

QBlowfish bf(secretKey);
QByteArray encryptedBa = bf.encrypted(clearText.toUtf8());
const char* cString = encryptedBa.constData();
QString saved = QString::fromUtf8(cString);
QByteArray decryptedBa = bf.decrypted(saved.toUtf8());

El resultado es este:

content to encryp:
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Arial'; font-size:12pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">HALLO</p></body></html>" 


cipherText (Input to decrypt): 


Now the strange part: If I switch the line

QByteArray decryptedBa = bf.decrypted(saved.toUtf8());


QByteArray decryptedBa = bf.decrypted(encryptedBa);

everythink works. BUT: The output is 100% the same, only that the decryptedBa at the end is a duplicate of contentas it should be. I am also wondering, why the cipherText has a " at the end. But that is the same for both versions. What am I missing here?


Following the tip from the answer below and the comments, I came up with this solution:

QString saved = encryptedBa.toBase64();
std::string stdString =  std::string(saved.toUtf8().data());
QByteArray fromSaved = QByteArray::fromBase64(;

The " at the end of the ciphertext is also gone, then.

preguntado el 28 de mayo de 14 a las 14:05

1 Respuestas

The cypher text is likely not UTF8 válido. This means that the data is not guaranteed to properly round-trip through QString::fromUtf8(data).toUtf8();.

Comprueba eso encryptedBa e saved.toUtf8() are actually exactly the same

contestado el 28 de mayo de 14 a las 14:05

how do I check that? What I want to do isn't so much special, so somebody should already know how save and restore... - user2366975

QByteArray overloads the operator!= por lo que sólo if(encryptedBa!=saved.toUtf8)qDebug()<<"cyphertext not valid utf8"; - monstruo del trinquete

Ah, I've been so far. So it is not. Even the lengthis not. And now I don't know what to do. - user2366975

@user2366975 don't convert to string, or use base64 if you need text compatible data - monstruo del trinquete

@user2366975 then convert to base64 which is designed to save binary data as text - monstruo del trinquete

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.