Qt 5.14.2 Cryptographic Armor - Analysis of Comprehensive Data Protection Tactics


In today's digital era, data security has been paid more and more attention. Whether it is private information or trade secrets, if they are stolen or tampered with, the harm they bring is self-evident. As programmers, we have the responsibility to build a solid and reliable protective cover for the system, so that data can be securely transmitted and encrypted stored in the cloud or local environment. Today, let's analyze the cryptography toolbox in Qt 5.14.2 to discuss how to protect data security in all directions.


1、 Data Security Overview

This section will guide readers to the basic knowledge of cryptography.

1. What is data encryption?

Data encryption is a process of converting plaintext data into ciphertext data, which makes it impossible for unauthorized people to directly read and understand the data content, thus protecting the confidentiality and integrity of data.

Specifically, encryption is to convert the original readable plaintext data into the unreadable ciphertext data by using the combination of key and encryption algorithm. Only when you have the correct key and use the same algorithm can you decrypt the ciphertext and regain the plaintext data.

Common encryption algorithms include symmetric encryption algorithms (such as AES DES, 3DES, etc.) and asymmetric encryption algorithms (such as RSA). In addition, hash algorithms (such as MD5 SHA series) can generate message digest for data to verify data integrity.

In short, data encryption is an important means to protect information security and ensure data transmission and storage security. It is widely used in network communication, mobile applications, cloud storage and other fields.


2. Why data encryption is needed?

Data encryption has the following main purposes:

(1) . Protect data privacy: Prevent sensitive information (such as personal privacy, financial data, etc.) from being stolen and disclosed during transmission or storage.

(2) Maintain data integrity: Detect whether the data is tampered or damaged during transmission.

(3) . Data identity authentication: Confirm the legitimacy and authenticity of the data source.

(4) . Non repudiation of data provided: The sender cannot deny that the data was sent.


3. How is symmetric encryption different from asymmetric encryption?

Symmetric encryption and asymmetric encryption are two common encryption methods. Their working principles and usage scenarios are different:

(1) , Symmetric Encryption

  • Use a single key for encryption and decryption

  • Use the same key for encryption and decryption

  • The key must be securely shared with both parties

  • Fast algorithm execution, suitable for encrypting large amounts of data

  • Common algorithms: AES DES, 3DES, RC4, etc

(2) , Asymmetric Encryption

  • Use a pair of keys: public key and private key

  • The public key is used for encryption and the private key is used for decryption

  • The public key can be made public, and the private key must be kept strictly confidential

  • The algorithm executes slowly, and is usually used for small data volume (such as key exchange)

  • Common algorithms: RSA ECC (elliptic curve encryption), etc

(3) Comparison of symmetric encryption and asymmetric encryption

  • Key sharing: symmetric encryption requires secure key sharing, and asymmetric encryption public key can be disclosed
  • Encryption and decryption speed: fast symmetric encryption, slow asymmetric encryption
  • Applicable scenarios:
    • Symmetric encryption is suitable for large amount of encrypted data transmission
    • Asymmetric encryption is suitable for key negotiation, digital signature, etc
  • Security:
    • Symmetric encryption security relies on key protection
    • Asymmetric encryption will compromise security if the private key is disclosed

Generally, for encrypted transmission of large amounts of data, asymmetric encryption is used to negotiate a symmetric encryption key first, and then symmetric encryption is used for encrypted transmission of data. This mode is widely used.


4. What is the hash algorithm?

Hash Algorithm is a one-way algorithm that maps any length of data input to a fixed length of small data string (hash value or message digest). It has the following characteristics:

(1) , one-way (Irreversibility)
The hash process is irreversible, and the original data cannot be inferred from the hash value. This makes hash algorithm very useful in applications such as data fingerprint and digital signature.

(2) Avalanche Effect
A small change in the input data will make a big difference in the output hash value. This can effectively prevent similar data from generating similar hash values.

(3) , Compression
No matter how long the input data is, the output hash value is fixed in length, usually 128 bits or 256 bits.

(4) . Collision Resistant
The ideal hash algorithm is difficult to find that two different inputs can produce the same hash value, and the probability of collision is extremely low.

Common hash algorithms are:

  • MD5 (128 bit hash value)
  • SHA-1 (160 bit hash value)
  • SHA-256, SHA-384, SHA-512 (256 bit, 384 bit, 512 bit hash values)

Hash algorithm is widely used, such as:

  • File integrity verification

  • digital signature

  • Password storage (no direct storage of password plaintext)

  • Message Authentication Code (MAC)

  • load balancing

  • Data de duplication

In a word, the hash algorithm plays an important role in data security, message authentication, data integrity verification and other scenarios by mapping arbitrary length data to short, fixed length hash values.


II Initial experience of QByteArray encryption

QByteArray not only provides basic byte array operations, but also built-in multiple encryption algorithms, which can realize symmetric encryption, hash encryption and Base64 encoding and decoding of data. First, let's experience QByteArray's cryptographic capabilities.

 QByteArray data = "Hello Qt Data Security! "; //AES 256 bit symmetric encryption QByteArray key = QByteArray::fromHex("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"); QByteArray encrypted = QMessageAuthenticationCode::hash(data,  key, QCryptographicHash::Sha256).toHex(); //MD5 hash encryption QByteArray hashValue = QCryptographicHash::hash(data,  QCryptographicHash::Md5).toHex(); //Base64 encoding QByteArray base64Data = data.toBase64();

3、 Analysis of Advanced AES Encryption Mode

The AES encryption provided by QByteArray is relatively simple and cannot meet the needs of more scenarios. Fortunately, Qt provides a special QAesXXX class that supports multiple encryption modes (ECB/CBC/CFB/OFB), as well as advanced options such as fill mode and initialization vector. This section will explain how to use it.

 QAesEncryption encryption(QAesEncryption::AES_256,  QAesEncryption::ECB); QByteArray key = QAesEncryption::generateKey(QAesEncryption::AES_256); encryption.setKey(key); QByteArray data = "Hello Qt AES Encryption! "; QByteArray encrypted = encryption.encrypt(data); QByteArray decrypted = encryption.decrypt(encrypted);

IV Qt random number generator (QRNG)

The security of the key is very important to the encryption algorithm. Qt provides a QRNG (Qt Random Number Generator) random number generator, which can generate high-intensity random numbers at the encryption level and provide high-intensity keys for encryption algorithms. Let's look at the specific use mode:

 char key[33]; uint64_t randomvalue; int ret; ret = qrandomseed();  // 1. Initialization ret = qrandomseed64(); // 2. Return entropy estimation in uint64 form qrandomcpuaes(key, 33, &randomvalue); // 3. Generate 32-bit AES encryption key

5、 Cross platform encryption case


Cross platform encryption of chat tools is a key problem that must be solved for chat tools and other applications that need end-to-end data transmission between different operating systems and devices. The following is a detailed case study and solution:


1. Cross platform challenges

When developing cross platform applications, we need to consider the compatibility problems caused by differences in operating systems, hardware architectures, compilation environments, etc. Encryption algorithms and key generation methods may differ slightly on different platforms, leading to encryption and decryption failures.


2. Unified encryption library

To solve this problem, we need to select a cross platform encryption library to ensure that all platforms use the same algorithm. Taking the Qt framework as an example, its QCA (Qt Cryptographic Architecture) module provides such cross platform encryption function support, including symmetric encryption (AES/DES/Blowfish, etc.), hash algorithm (MD5/SHA1/SHA256, etc.), key generation, digital signature, etc.

3. Key agreement and key management

We need to negotiate and share a symmetric encryption key for both chat parties. This can be achieved using asymmetric encryption algorithms such as RSA.

  • Each client generates its own RSA key pair (public key and private key)

  • Send the public key to each other

  • Encrypt a randomly generated AES session key with the other party's public key and send it to the other party

  • The other party uses its own private key to decrypt and obtain the AES session key

  • Both parties use the AES session key to encrypt chat data for communication


4. Data encryption transmission process

 #include <QCoreApplication> #include <QCA> #include <QDebug> //Generate RSA key pair void generateRSAKeyPair(QCA::PrivateKey &privateKey,  QCA::PublicKey &publicKey) { QCA::InitializationVector iv = QCA::InitializationVector::fromByteArray(QCA::Random::randomize(16).toByteArray()); QCA::KeyLength keySize = QCA::KeyLength(2048); QCA::RSA_PrivateKey privateRSAKey(keySize,  iv); privateKey = privateRSAKey.toPEM(); publicKey = privateRSAKey.toPublicKey(); } int main(int argc,  char *argv[]) { QCoreApplication a(argc,  argv); //Generate RSA key pairs for sender and receiver QCA::PrivateKey senderPrivateKey, receiverPrivateKey; QCA::PublicKey senderPublicKey, receiverPublicKey; generateRSAKeyPair(senderPrivateKey,  senderPublicKey); generateRSAKeyPair(receiverPrivateKey,  receiverPublicKey); //Sender: generate an AES session key, encrypt it with the receiver's public key, and send it to the receiver QCA::SymmetricKey chatKey = QCA::SymmetricKey::generateKey("aes256", 32,  QCA::SymmetricKey::EncodingHex); QCA::PublicKey receiverPubKey(receiverPublicKey.toPEM()); QCA::SecureArray encryptedKey = chatKey.toByteArray().encrypt(receiverPubKey); //AES key after simulated network transmission encryption qDebug() << "Encrypted AES Key:" << encryptedKey.toByteArray().toHex(); //Receiver: use its own private key to decrypt and obtain the AES key QCA::PrivateKey myPrivateKey(receiverPrivateKey.toPEM()); QCA::SecureArray decryptedKey = encryptedKey.toByteArray().decrypt(myPrivateKey); QCA::SymmetricKey receivedChatKey(decryptedKey); //Sender: use AES key to encrypt chat data and send it to receiver QByteArray plainText = "Hello,  this is a secret message! "; QCA::Cipher cipher(QCA::CipherMode::CBC,  QCA::MessageAuthenticationCode::HMAC_SHA256, QCA::InitializationVector(16)); cipher.setup(chatKey); QByteArray encryptedMsg = cipher.update(plainText); //Simulate network transmission of encrypted chat data qDebug() << "Encrypted Message:" << encryptedMsg.toHex(); //Receiver: use AES key to decrypt chat data QCA::Cipher receiveCipher(QCA::CipherMode::CBC,  QCA::MessageAuthenticationCode::HMAC_SHA256, QCA::InitializationVector(16)); receiveCipher.open(QCA::CipherMode::Decode,  receivedChatKey); QByteArray decryptedMsg = receiveCipher.update(encryptedMsg); qDebug() << "Decrypted Message:" << decryptedMsg; return a.exec(); }

In the above example, we simulated the key negotiation and encrypted data transmission between the sender and receiver. The main steps are as follows:

  1. use generateRSAKeyPair The function generates respective RSA key pairs for the sender and receiver.
  2. The sender generates a random AES session key chatKey , use the receiver's public key receiverPublicKey Encrypt the encrypted key encryptedKey Send to receiver.
  3. The receiver uses its own private key receiverPrivateKey Decryption acquisition chatKey
  4. Used by sender chatKey Encrypt clear text messages plainText , get the encrypted message encryptedMsg And send it to the receiver.
  5. Decrypted by the receiver before use chatKey , decrypt the received encrypted message encryptedMsg , get the original plaintext message decryptedMsg

In this example, we use the RSA asymmetric encryption algorithm provided by the QCA library for key negotiation, and use the AES symmetric encryption algorithm to encrypt and transmit chat data. CBC mode and HMAC-SHA256 message authentication code are also used to improve the integrity protection of encrypted data.


In short, Qt provides programmers with a comprehensive cryptography toolbox. Only by mastering the use of relevant APIs, can we write safe and reliable programs. In the future, perhaps the development of quantum computing will completely change the face of cryptography, but at present, it is our duty to follow known best practices. Protecting data is protecting the world!

  • seventeen
    give the thumbs-up
  • step on
  • twenty
    Collection
    Think it's good? One click collection
  •  Reward
    Reward
  • zero
    comment
Command line: -prefix /home/liuyh/workspace/ qt5 . fourteen point two -arm -opensource -confirm-license -release -strip -shared -xplatform linux-arm-gnueabi-g++ -optimized-qmake -c++std c++11 --rpath=no -pch -skip qt 3d -skip qt active qt -skip qt androidextras -skip qt canvas3d -skip qt connectivity -skip qt datavis3d -skip qt doc -skip qt gamepad -skip qt location -skip qt macextras -skip qt networkauth -skip qt purchasing -skip qt remoteobjects -skip qt script -skip qt scxml -skip qt sensors -skip qt speech -skip qt svg -skip qt tools -skip qt translations -skip qt wayland -skip qt webengine -skip qt webview -skip qt winextras -skip qt x11extras -skip qt xmlpatterns -make libs -make examples -nomake tools -nomake tests -gui -widgets -dbus-runtime --glib=no --iconv=no --pcre= qt --zlib= qt -no-openssl --freetype= qt --harfbuzz= qt -no-opengl -linuxfb --xcb=no -tslib --libpng= qt --libjpeg= qt --sqlite= qt -plugin-sql-sqlite -I/opt/tslib/include -L/opt/tslib/lib -recheck-all executing config test machineTuple + arm-linux-gnueabi-g++ -dumpmachine > sh: 1: arm-linux-gnueabi-g++: not found test config. qt base.tests.machineTuple FAILED executing config test verifyspec + cd /home/liuyh/workspace/ QT5 . fourteen point two / qt -everywhere-src- five point one four .2/config.tests/verifyspec && /home/liuyh/workspace/ QT5 . fourteen point two / qt -everywhere-src- five point one four .2/ qt base/bin/qmake "CONFIG -= qt debug_and_release app_bundle lib_bundle" "CONFIG += shared warn_off console single_arch" 'QMAKE_LIBDIR += /opt/tslib/lib' 'INCLUDEPATH += /opt/tslib/include' -early "CONFIG += cross_compile" /home/liuyh/workspace/ QT5 . fourteen point two / qt -everywhere-src- five point one four .2/ qt base/config.tests/verifyspec + cd /home/liuyh/workspace/ QT5 . fourteen point two / qt -everywhere-src- five point one four .2/config.tests/verifyspec && MAKEFLAGS= /usr/bin/make clean && MAKEFLAGS= /usr/bin/make > rm -f verifyspec.o > rm -f *~ core *.core > arm-linux-gnueabi-g++ -c -O2 -march=armv7-a -mtune=cortex-a7 -mfpu=neon -mfloat-abi=hard -O2 -march=armv7-a -mtune=cortex-a7 -mfpu=neon -mfloat-abi=hard -pipe -O2 -w -fPIC -I/home/liuyh/workspace/ QT5 . fourteen point two / qt -everywhere-src- five point one four .2/ qt base/config.tests/verifyspec -I. -I/opt/tslib/include -I/home/liuyh/workspace/ QT5 . fourteen point two / qt -everywhere-src- five point one four .2/ qt base/mkspecs/linux-arm-gnueabi-g++ -o verifyspec.o /home/liuyh/workspace/ QT5 . fourteen point two / qt -everywhere-src- five point one four .2/ qt Base/config. tests/verifyspec/verifyspec. cpp>make: arm linux gnueabi-g++: command not found>make: * * * [Makefile: 172: verifyspec. o] error 127
06-09

Is "relevant recommendation" helpful to you?

  • Very unhelpful
  • No help
  • commonly
  • to be helpful to
  • Very helpful
Submit
comment
Add Red Packet

Please fill in the red envelope greeting or title

individual

The minimum number of red packets is 10

element

The minimum amount of red packet is 5 yuan

Current balance three point four three element Go to recharge>
To be paid: ten element
Achieve 100 million technicians!
After receiving, you will automatically become a fan of the blogger and the red envelope owner rule
hope_wisdom
Red packet sent

Reward the author

W rain or shine w

Your encouragement will be the greatest impetus for my creation

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
Scan code for payment: ¥1
Obtaining
Scan code for payment

Your balance is insufficient, please change the scanning code to pay or Recharge

Reward the author

Paid in element
Payment with balance
Click to retrieve
Scan code for payment
Wallet balance zero

Deduction description:

1. The balance is the virtual currency of wallet recharge, and the payment amount is deducted at a ratio of 1:1.
2. The balance cannot be directly purchased and downloaded, but VIP, paid columns and courses can be purchased.

Balance recharge