Three __linux of security programming using QCA in C + + GUI qt

Source: Internet
Author: User
Tags openssl netbeans

The previous two articles introduced the installation and configuration of the QCA framework, and in this article I will begin writing a digital certificate based encryption routine to explain the use of the QCA framework. In fact, QCA's application is very simple, and in the source code release package also comes with a lot of examples (in the Qca-2.0.3\examples directory), basically can solve our daily encryption and decryption programming work.

As usual, let's introduce the development environment: Operating system: Windows7 32-bit version. Qt sdk:4.8.5 Version (Installation path: C:\Qt\4.8.5). QCA sdk:2.0.3 version. openssl:1.0.0g version, QCA dependent library, and used to generate a digital certificate file. Ide:netbeans IDE 7.3.1 C + + version.

First of all, using OpenSSL to generate a test with a digital certificate, the Internet has an introduction OpenSSL to generate digital certificates, so I will not repeat the introduction, if you are lazy, do not want to see the article generated their own digital certificates, I have provided a test with a digital certificate, So that you can run this routine normally, at the end of the article I provide the entire routine source code, which contains the test digital certificate (in the ETC directory). Then we open NetBeans and create a new QT-type Application project. In my previous article, I introduced the use of NetBeans for C/s + + development of the article, interested students can go to see, overall, in the C/s + + IDE, NetBeans than Qt creator and Eclipse better (except VC + +, Because we use the GCC compiler).

After the project is created, the approximate directory structure is shown in the following illustration:

(Figure I)

Here we are concerned with the certificatecrypto.h and certificatecrypto.cpp files, as follows:

#ifndef certificatecrypto_h
#define	certificatecrypto_h

#include <QtCore/qdir.h>
#include <QtCore/qstring.h>
#include <QtCore/qbytearray.h>

const qstring Cert_file_dir = "etc";

Class Certificatecrypto
{public
:
    explicit Certificatecrypto ();
    Virtual ~certificatecrypto ();

    BOOL Encrypt (const Qbytearray &in, Qbytearray *out);
    QString Tohex (const qbytearray &in);

Private:
    qdir m_certfiledir;

#endif/	* certificatecrypto_h * *

In the header file we define the path of the digital certificate and the cryptographic function. Next look at the implementation class:

#include "certificatecrypto.h" #include <QtCore/qdatetime.h> #include <QDebug> #include <qtcrypto/ Qca.h>/** * Constructor/Certificatecrypto::certificatecrypto (): M_certfiledir (Cert_file_dir) {}/** * destructor/CERT Ificatecrypto::~certificatecrypto () {}/** * Certificate encryption * @param in * @param out * @return */bool Certificatecrypto::en

    Crypt (const qbytearray& in, qbytearray* out) {//1. Initialize QCA qca::initializer;

    Qca::securearray encrypt; 2. Check if the system supports QCA plug-ins if (! qca::issupported ("cert")) {Qdebug ("Sorry, the current system does not support digital certificates.)
    ");

        else {QString cert_file = M_certfiledir.absolutefilepath ("Server.cer"); 3.
        Load digital certificate Qca::convertresult result;
        Qca::certificate cert = Qca::certificate::frompemfile (Cert_file, &result); 
            if (result = = Qca::convertgood) {//4. Check digital certificate validity period Qdatetime before = Cert.notvalidbefore (); Qdatetime after = Cert.notvalidafteR ();
            Qdatetime now = Qdatetime::currentdatetime (); if (now >= before && today <= after) {//5. Get the public key in a digital certificate QCA::P ublic
                Key Pub_key = Cert.subjectpublickey (); if (Pub_key.canencrypt ()) {//6. Encrypt encrypt with public key = Pub_key.encrypt (i
                    n, qca::eme_pkcs1v15);
                    Out->clear ();
                    Out->append (Encrypt.tobytearray ());
                return true; else {qdebug ("Sorry, the current digital certificate does not support encryption.")
                "); } else {qdebug ("Sorry, the current digital certificate has expired.")
            "); } else {qdebug ("Sorry, failed to load digital certificate.")
        ");
return false; /** * Convert to 16-@param encrypt * @return/QString Certificatecrypto::tohex (const qbytearray& in) {RE
Turn Qca::arraytohex (in); }

The implementation of the class is very easy to understand, I do not have to say anything, I believe that students by virtue of the comments in the code should know each piece of code to achieve the intent. Here are just a few important points to focus on:

1. Before using QCA, you must initialize the call to it, otherwise QCA will not work, that is, "Qca::initializer qca_init" in the code.

2. It is best to check to see if the current provider implementation supports the cryptographic algorithm before invoking the QCA related encryption algorithm, such as in code: if (! qca::issupported ("cert"), is to check whether to support digital certificates, some students will certainly ask, how to know the issupported function of the algorithm string parameters. In fact, in the previous article we have already talked about, is to use the Qcatool2 tool, in the command line, enter "Qcatool2 plugins--debug", and then display a lot of algorithm names in the issupported function is to use the algorithm name of the string. As in my development environment, as shown in the following illustration:

(Figure II)

3. QCA-OSSL provider's digital certificate algorithm implementation is to support a variety of methods to load the certificate, in my code is the use of file loading, in addition to support string loading and byte array loading mode, according to the actual application environment can choose different certificate load functions.

4. The ciphertext returned by QCA is a Qca::securearray object, so it can be converted to a byte array (Qbytearray) for subsequent processing.

5. To compile and link the QCA library, you must make some necessary settings, as shown in the following illustration:

(Figure III)

In the Project Properties dialog box, click "Qt", in the Right box, select "Custom definition" next to the button, pop-up Custom Definition dialog box, click the "Add" button, enter "CONFIG + + crypto", and finally click Save.

Do you remember the Crypto.prf file (in the%%qtdir%\mkspecs\features directory) that we defined in the first article in this series? In this file, the QCA header file directory and the library file directory are defined. Qt reads the configuration file when it compiles the application, obtaining information about compilation and linking.

OK, now we can run the program (other related code is no longer introduced, it is the basic programming of some QT GUI), as shown in the following figure:

(Figure IV)

The program displays a main form and a OK button, and clicking the OK button displays the encrypted string in the text box (clear: "Hello world!" ), as shown in the following illustration:

(Figure V)

At this point, our application development is complete, overall QCA development is not very difficult, basically API design is very friendly. It is ideal for QT developers (including myself) who are transformed from Java. In the next article, we'll look at how to package the QCA routine and release it as an application installation package that is out of the QT development environment.

Provide This example routines code package download, a total of learning reference: Qca_demo.rar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.