QT simple string encryption and decryption

Plus performed using a bitwise XOR ^ decryption:

Encryption and decryption are using this function:

void EncryptionStr(QByteArray &data)
{
    static QByteArray key = "MY_KEY";
    for (int i = 0; i < data.size(); i++)
    {
        data[i] = data[i] ^ key[i % key.size()];
    }
}

It found that the encryption function can not be encrypted on the Chinese, because each contains Chinese characters differ in the number of different encoding formats occupied bytes. Therefore the string to wide bytes (two bytes per character), after treatment conversion utf8 (I project the utf8 character encoding).

QString EncryptionStr(QString str)
{
    std::wstring wString = str.toStdWString();
    static QByteArray key = "MY_KEY";
    for (int i = 0; i < wString.size(); i++)
    {
        wString[i] = wString[i] ^ key[i % key.size()];
    }
    return QString::fromStdWString(wString).toUtf8();
}

Note: Here encryption key characters when the same encryption abnormal characters, such as a key = "MY_KEY" encrypted MY_KEY after the encrypted ciphertext is empty because the XOR operation when the same value the result is 0, so that after the encrypted ciphertext is "\ 0" is the terminator of the string, leading to abnormal encryption.

Solution: The key value is set to a string of characters not in plain text, such as ¥ ~ and other special characters.

Guess you like

Origin blog.csdn.net/qq_23903863/article/details/81163998