
Originally Posted by
freely
Yes of course it is one of the cases.
I understand Unicode,Asci,Latin,UTF and I have read the Qt Framework documentation
I need to convert
QString to
QByteArray and vice versa so as not to loose any data while converting
How to accomplish such conversion?
But why exactly do you want this conversion to take place? If you want to xor the string then just do it. Each QChar is a 16 bit value, just xor it with 16 bits of your key and you'll get two 8b values that you can store in the byte array.
int keyIndex = 0;
for(int i=0;i<string.size();++i){
quint16 val = string.at(i).unicode();
char high = key.at(keyIndex++);
if(keyIndex==key.size()) keyIndex = 0;
char low = key.at(keyIndex++);
if(keyIndex==key.size()) keyIndex = 0;
quint16 keyPiece = ((high & 0xFF) << 8) | (low & 0xFF));
quint16 encoded = val ^ keyPiece;
result.append(encoded >> 8);
result.append(encoded & 0xFF);
}
return result;
}
QByteArray xorEncrypt(const QString &string, const QByteArray &key){
QByteArray result;
int keyIndex = 0;
for(int i=0;i<string.size();++i){
quint16 val = string.at(i).unicode();
char high = key.at(keyIndex++);
if(keyIndex==key.size()) keyIndex = 0;
char low = key.at(keyIndex++);
if(keyIndex==key.size()) keyIndex = 0;
quint16 keyPiece = ((high & 0xFF) << 8) | (low & 0xFF));
quint16 encoded = val ^ keyPiece;
result.append(encoded >> 8);
result.append(encoded & 0xFF);
}
return result;
}
To copy to clipboard, switch view to plain text mode
Decoding is similar, you just need to reassemble the string.
Of course be aware that xor is a very lousy "cipher" that can be broken within a couple of seconds, especially when encoding data consisting mostly of 0x00:
0x00 xor SECRET = SECRET
The easiest way to break xor is to feed it with a message (either plaintext or ciphertext) consisting of zeroes. Then the key will reveal itself during encryption/decryption.
Bookmarks