Andrei Yankovich
June 14, 2019, 4:10 p.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
    1. cd yourRepo
  • Add Qt-Secret in your repository, for example, a submodule
    1. The git add submodule https://github.com/QuasarApp/Qt-Secret.git
  • Update your submodules

    1. git submodule update --init --recursive

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

    1. 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.
  1. #include <qrsaencryption.h> // Include the Qt-Secret library (RSA)
  2.  
  3. QByteArray pub, priv; // Create variables to keys.
  4. QRSAEncryption e; // Create a variable to cryptographer
  5.  
  6. // Generate a pair of keys with a bit depth of 128
  7. e.generatePairKey (pub, priv, QRSAEncryption :: Rsa :: RSA_128); // or QRSAEncryption :: Rsa :: RSA_64
  8. QByteArray msg = "test message";
  9.  
  10.  
  11. auto encodeData = e.encode (msg, pub); // encrypt the message with the public key
  12. auto decodeData = e.decode (encodeData, priv); // decrypt with the private key
  13.  
  14. qDebug () << decodeData; // check in the message.
  15.  
  16.  
  17.  
Signature and verification of message signature.
  1. #include <qrsaencryption.h>
  2.  
  3. // Initialization
  4. QByteArray pub, priv;
  5. QRSAEncryption e;
  6. e.generatePairKey (pub, priv, QRSAEncryption :: Rsa :: RSA_128); // or QRSAEncryption :: Rsa :: RSA_64
  7.  
  8. QByteArray msg = "test message";
  9.  
  10. auto signatureMessage = e.signMessage (msg, priv); // sign the message
  11.  
  12. if (e.checkSignMessage (signatureMessage, pub)) {// check the signature
  13. // message signed successfully
  14. }
  15.  

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.

Recommended articles on this topic

By article asked1question(s)

7

Do you like it? Share on social networks!

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

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

Andrei Yankovich
  • Jan. 17, 2020, 1:31 p.m.

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

Дмитрий
  • April 21, 2020, 3:15 p.m.

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

Andrei Yankovich
  • May 20, 2020, 6:39 p.m.

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

ИБ
  • Nov. 11, 2020, 7:41 p.m.

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

Q
  • July 16, 2021, 4:28 p.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup