Документация
ОС Аврора 5.0.1

publickeyexample.cpp

В приведённом ниже коде показано, как выполнять шифрование, дешифрование, подпись и проверку с открытым ключом.

/*
 Copyright (C) 2003 Justin Karneges <justin@affinix.com>
 Copyright (C) 2005 Brad Hards <bradh@frogmouth.net>
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
 
#include <QtCrypto>
 
#include <QCoreApplication>
 
#include <iostream>
 
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
 
int main(int argc, char **argv)
{
    // Объект Initializer настраивает элементы, а также
    // выполняет очистку, когда они больше не требуются.
    QCA::Initializer init;
 
    QCoreApplication app(argc, argv);
 
    // Нужно убедиться, что поддерживается обработка сертификатов.
    if (!QCA::isSupported("cert")) {
        std::cout << "К сожалению, сертификат PKI не поддерживается" << std::endl;
        return 1;
    }
 
    // Считывает закрытый ключ.
    QCA::PrivateKey    privKey;
    QCA::ConvertResult convRes;
    QCA::SecureArray   passPhrase = "start";
    privKey                       = QCA::PrivateKey::fromPEMFile(QStringLiteral("Userkey.pem"), passPhrase, &convRes);
    if (convRes != QCA::ConvertGood) {
        std::cout << "К сожалению, не удалось импортировать закрытый ключ" << std::endl;
        return 1;
    }
 
    // Чтение соответствующего сертификата открытого ключа.
    // Его также можно организовать с помощью метода fromPEMFile().
    QCA::Certificate pubCert(QStringLiteral("User.pem"));
    if (pubCert.isNull()) {
        std::cout << "К сожалению, не удалось импортировать сертификат открытого ключа" << std::endl;
        return 1;
    }
    // Сертификат встраивается в объект SecureMessageKey через
    // CertificateChain.
    QCA::SecureMessageKey secMsgKey;
    QCA::CertificateChain chain;
    chain += pubCert;
    secMsgKey.setX509CertificateChain(chain);
 
    // На основе сертификата открытого ключа создаётся объект SecureMessage.
    QCA::CMS           cms;
    QCA::SecureMessage msg(&cms);
    msg.setRecipient(secMsgKey);
 
    // Некоторый простой текст — используется первый аргумент командной строки, если он предоставлен.
    QByteArray plainText = (argc >= 2) ? argv[1] : "What do ya want for nuthin'";
 
    // Теперь объект SecureMessage используется для шифрования простого текста.
    msg.startEncrypt();
    msg.update(plainText);
    msg.end();
    // Вероятно, для этого разумно подождать 1 секунду.
    msg.waitForFinished(1000);
 
    // Проверка, сработал ли алгоритм.
    if (!msg.success()) {
        std::cout << "Ошибка шифрования: " << msg.errorCode() << std::endl;
        return 1;
    }
 
    // Получение результата.
    QCA::SecureArray cipherText = msg.read();
    QCA::Base64      enc;
    std::cout << plainText.data() << " шифрует в (в base 64): ";
    std::cout << qPrintable(enc.arrayToString(cipherText)) << std::endl;
 
    // Демонстрирует, что можно расшифровать сообщение с помощью закрытого ключа.
    if (!privKey.canDecrypt()) {
        std::cout << "Закрытый ключ нельзя использовать для расшифровки" << std::endl;
        return 1;
    }
    QCA::SecureArray plainTextResult;
    if (0 == privKey.decrypt(cipherText, &plainTextResult, QCA::EME_PKCS1_OAEP)) {
        std::cout << "Ошибка процесса дешифрования" << std::endl;
        return 1;
    }
 
    std::cout << qPrintable(enc.arrayToString(cipherText));
    std::cout << " (в base 64) расшифровывается в: ";
    std::cout << plainTextResult.data() << std::endl;
 
    return 0;
}

Мы используем cookies для персонализации сайта и его более удобного использования. Вы можете запретить cookies в настройках браузера.

Пожалуйста ознакомьтесь с политикой использования cookies.