Andrei Yankovich
Andrei YankovichJune 14, 2019, 6:10 a.m.

Data encryption by RSA algorithm in Qt with public and private keys without binding to OpenSSL

Introduction

In this article there is a way how to organize message encryption, as well as use RSA (public and private keys) algorithms without libraries similar to OpenSSL, QCA or LibSodium.


How does it work?

Why is it necessary?

There are many encryption algorithms, most of them are based on an idea that in a message you've got there is a key to encrypt your message and send it to the recipient. It is assumed that the recipient has already got the encryption key so the recipient can decrypt it. However this method isn't usable in any case , because the encryption key should somehow sent the way nobody can intercept it,but this is almost impossible.

That's why nowadays the RSA encryption method using public and private key (asynchronous encryption) has become the most reliable and popular.

The working principle is the following:
As an example, we use the already established names of encryption participants: Alice and Bob.
Suppose Alice wants to send Bob a secret message, but doesn't want anyone else to see it.

  • Bob creates two keys for this operation: public and private.

  • Bob sends the public key to Alice.

  • Alice encrypts the message with the Bob’s public key.

  • Alice sends the encrypted message to Bob.

  • Bob decrypts Alice's message with a private key.

Eve, who wants to find out what Alice and Bob correspond with, intercepts all their messages. She cannot do anything with them, because she hasn't got their private keys, since in the RSA algorithm the encrypted message with key A (public key) can be decrypted only by its A1 pair (private key).
Thus, you can easily and conveniently protect the important information.

Description.

Qt-Secret is a simple library created by the QuasarApp group on Qt / qmake, the goal is to provide Basic encryption opportunities, which lack in the native Qt. Namely: RSA and AES algorithms.

Key features:

  • Generation of RSA64 and RSA128 key pairs (it is supposed to support quantity of numbers up to RSA2048)
  • Encryption and Decryption RSA.
  • Signature and message authentication.
  • AES key generation (AES64, AES128, AES256)
  • Encryption and Decryption AES

Working with Qt-Secret

Build the library and add it in a project using qmake

  • Open your repository
    cd yourRepo
  • Add Qt-Secret in your repository, for example, a submodule
    The git add submodule https://github.com/QuasarApp/Qt-Secret.git
  • Update your submodules

    git submodule update --init --recursive

  • Add your "pri" Qt-Secret library file in your "pro" file.

    include ($$PWD/Qt-Secret/src/Qt-Secret.pri)

  • Rebuild the project

The library is added in your project, now you can use it.

An example of using

Encrypting and decrypting messages.
#include <qrsaencryption.h> // Include the Qt-Secret library (RSA)

QByteArray pub, priv; // Create variables to keys.
QRSAEncryption e; // Create a variable to cryptographer

// Generate a pair of keys with a bit depth of 128
e.generatePairKey (pub, priv, QRSAEncryption :: Rsa :: RSA_128); // or QRSAEncryption :: Rsa :: RSA_64
QByteArray msg = "test message";


auto encodeData = e.encode (msg, pub); // encrypt the message with the public key
auto decodeData = e.decode (encodeData, priv); // decrypt with the private key

qDebug () << decodeData; // check in the message.



Signature and verification of message signature.
#include <qrsaencryption.h>

// Initialization
QByteArray pub, priv;
QRSAEncryption e;
e.generatePairKey (pub, priv, QRSAEncryption :: Rsa :: RSA_128); // or QRSAEncryption :: Rsa :: RSA_64

QByteArray msg = "test message";

auto signatureMessage = e.signMessage (msg, priv); // sign the message

if (e.checkSignMessage (signatureMessage, pub)) {// check the signature
// message signed successfully
}

Conclusion

This library is a good solution for simple encryption tasks.

  • easy to include;
  • easy to use.

It's good to use a pair of keys for one working session.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

D
  • Jan. 16, 2020, 12:06 p.m.

Доброго времени суток, не подскажите, что делать в данной ситуации, после того, как я сделал все вышеуказанные инструкции для подключения библиотеки к проекту?

Andrei Yankovich
  • Jan. 17, 2020, 2:31 a.m.

Выглядит как ошибка библиотеки. Расскажите подробно на какой платформе вы собираете проект (MinGW или MSVC) их версии и версии Qt.

Дмитрий
  • April 21, 2020, 5:15 a.m.

Та же самая ошибка. MinGW, Qt 5.14.2

Andrei Yankovich
  • May 20, 2020, 8:39 a.m.

Для тех у кого возникает ошибка cannot find -lQt-Secret1, cannot find -lQtBigInt6
Решение и описание проблеммы здесь

ИБ
  • Nov. 11, 2020, 8:41 a.m.

Библиотека подключилась нормально, только на выводе из первого примера выходит пустое сообщение, вместо "test message" просто "". Никаких ошибок не выдает.

Q
  • July 16, 2021, 6:28 a.m.

Возможно ли с помощью этой библиотеки шифровать файлы, а не обычные строки?

Comments

Only authorized users can post comments.
Please, Log in or Sign up
m

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

  • Result:85points,
  • Rating points6
в

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

  • Result:50points,
  • Rating points-4
l

C++ - Test 005. Structures and Classes

  • Result:91points,
  • Rating points8
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
AC
Alexandru CodreanuJan. 19, 2024, 11:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…
BlinCT
BlinCTDec. 27, 2023, 8:57 a.m.
Растягивать Image на парент по высоте Ну и само собою дял включения scrollbar надо чтобы был Flickable. Так что выходит как то так Flickable{ id: root anchors.fill: parent clip: true property url linkFile p…
Дмитрий
ДмитрийJan. 10, 2024, 4:18 a.m.
Qt Creator загружает всю оперативную память Проблема решена. Удалось разобраться с помощью утилиты strace. Запустил ее: strace ./qtcreator Начал выводиться весь лог работы креатора. В один момент он начал считывать фай…
Evgenii Legotckoi
Evgenii LegotckoiDec. 12, 2023, 6:48 a.m.
Побуквенное сравнение двух строк Добрый день. Там случайно не высылается этот сигнал textChanged ещё и при форматировани текста? Если решиать в лоб, то можно просто отключать сигнал/слотовое соединение внутри слота и …

Follow us in social networks