Qt/C++ - Tutorial 069. XOR Encryption

XOR, cmake, Qt

XOR-encryption is the application of a key through bitwise exclusive OR to the source text. The mechanism of the bitwise exclusive is the following:

X Y X⊕Y
0 0 0
0 1 1
1 0 1
1 1 0

Thus, when executing an exclusive OR, there will always be a zero value if the variables have the same values.

The peculiarity of XOR is that one and the same function can both encrypt data and decrypt it. This is a simple method of data encryption, which can be hacked quickly enough if there is a large enough encrypted text, or a large password dictionary. But nevertheless, this can already be used for small initial data protection.

In the context of Qt, the use of XOR is no different from how the program was written without using Qt. The question here is how to extract data for encryption from QString objects, for example, if the text was entered in QTextEdit.

To do this, write a program that contains:

  • QTextEdit, In which the text will be entered, which will be encrypted.
  • QLineEdit, In which the encryption key will be entered.
  • QPushButton, In the slot of the click handler of which, data encryption / decryption will be performed. Again, I note that the method will be used the same.

The program will look like this:

Project structure

The project is written using CMake, so the structure will be as follows:

  • CMakeLists.txt
  • main.cpp
  • EncoderWidget.h
  • EncoderWidget.cpp

Encryption / decryption function

To implement encryption / decryption it is necessary:

  • The presence of a char array with the original data
  • Length of the array with the original data
  • Key as array char
  • Length of key
  • And also an array with output data.
const char* input;
int inputLength;
const char* key;
int keyLength;

char output[inputLength];

for (int i = 0; i < inputLength + 1; ++i)
{
    output[i] = input[i] ^ key[i % keyLength + 1];
}

Slot handler for encryption

As already mentioned, to encrypt the text, you need to correctly extract data from the input fields. To do this, you need to translate the text in the form of a QString string into a QByteArray from which to extract the data in the form of const char *. And also take the length of this data.

There is one point. This from QString in QByteArray is translated using the toLatin1 () method, which will result in data to the ASCII table, which will lead to data corruption if the text was written in Cyrillic. That is, this approach to encryption will be relevant if only symbols from the ASCII table are used, for example, for the login and password.

void EncoderWidget::encodeDecode()
{

    const char* input = m_textEdit->toPlainText().toLatin1().data();
    int inputLength = m_textEdit->toPlainText().toLatin1().length();
    const char* key = m_keyLineEdit->text().toLatin1().data();
    int keyLength = m_keyLineEdit->text().toLatin1().length();

    char output[inputLength];

    for (int i = 0; i < inputLength + 1; ++i)
    {
        output[i] = input[i] ^ key[i % keyLength + 1];
    }

    m_textEdit->setText(QString::fromLatin1(output, inputLength));
}

Conclusion

The project can be downloaded from the following link

10% refund of hotel reservation amount on Booking
10% refund of hotel reservation amount on Booking
We offer a link with a 10% return on the amount of the order when booking a hotel through Booking
Support the author Donate

Шифрует/дешифрует текст от 8 символов, так и должно быть?

Не обратил внимания на это, Проверял с большим текстом.. По идее не должно.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
N
June 25, 2019, 2:41 p.m.
Nico03

C++ - Test 001. The first program and data types

  • Result:40points,
  • Rating points-8
S
June 25, 2019, 9:16 a.m.
SabaNtuy

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:40points,
  • Rating points-8
SZ
June 24, 2019, 5:49 p.m.
Serg Zhi

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
Last comments
June 24, 2019, 10:23 a.m.
Евгений Легоцкой

Хорошо, ну будут проблемы помимо того, что касается статей, то не стесняйтесь задавать вопросы на форуме.
МБ
June 24, 2019, 10:21 a.m.
Михаил Булатов

Извиняюсь, все работает(из-за невнимательности).
June 24, 2019, 9:52 a.m.
Евгений Легоцкой

Придётся делать ещё сигнал в дочернем qml и пробрасывать через коннекты и обработчики. А вообще нужно смотреть конкретный код и что вы пытаетесь сделать. Так что лучше будет, если вы зад...
June 21, 2019, 8:31 a.m.
Ruslan Polupan

Вот моя строка по которой все отлично сработало %cqtdeployer% -bin c:/CentralMposKeys/CentalMposKeys.exe -qmake c:/Qt/5.12.2/mingw73_64/bin/qmake.exe
June 21, 2019, 8:24 a.m.
Андрей Янкович

Возможно кому то пригодится сqtdeployer для windows работает точно так же как и для Linux разница лишь в команде запуска Linux: cqtdeployer Windows: %cqtdeployer...
Now discuss on the forum
June 25, 2019, 6:16 p.m.
Алексей Внуков

только через webengine, прямого апи у Яндекса нет, вроде что-то есть у гугла, сам только начал интересоваться этим вопросом
June 25, 2019, 5:05 p.m.
Михаиллл

Само заработало. Странно.
June 25, 2019, 2:32 p.m.
Михаиллл

Похоже глюк вебсокета. К другим вебсокетам подключаюсь.
June 25, 2019, 1:55 p.m.
Андрей Янкович

падало потому что boolStatus был на стеке метода, после завершения метода переменная убивалась, и на обращении к ней было падение.просто сделай вот так: connect(&t, &QTimer::timeou...
June 25, 2019, 10:55 a.m.
IscanderChe

По пункту 3 попытался переписать метод setData. В итоге комбобокс перестал работать. bool MySqlTableModel::setData(const QModelIndex& index, const QVariant& value, int /* role */){...
Looking for a Job?
10,000.00 руб. - 15,000.00 руб.
Нужен помощник для создания API.
Moscow, Moscow, Russia
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB