view ui/sslhelp.cpp @ 1395:a2574a029322

Fix Base 64 signature size calculation. If the signature byte size is not equally dividable by three the base 64 encoding needs three additional bytes. The value is now fixed to avoid such errors in the future.
author Andre Heinecke <andre.heinecke@intevation.de>
date Mon, 26 Jan 2015 13:17:32 +0100
parents f3e2df6b49ba
children
line wrap: on
line source
/* Copyright (C) 2014 by Bundesamt für Sicherheit in der Informationstechnik
 * Software engineering by Intevation GmbH
 *
 * This file is Free Software under the GNU GPL (v>=2)
 * and comes with ABSOLUTELY NO WARRANTY!
 * See LICENSE.txt for details.
 */
#include "sslhelp.h"
#include <polarssl/sha256.h>
#include <polarssl/sha1.h>
#include <polarssl/pk.h>
#include <polarssl/entropy.h>
#include <polarssl/ctr_drbg.h>
#include <QApplication>
#include <QUuid>
#include <QDebug>

QString getPolarSSLErrorMsg(int ret)
{
    char errbuf[1020];
    polarssl_strerror(ret, errbuf, 1020);
    errbuf[1019] = '\0'; /* Just to be sure */
    return QString::fromLatin1(errbuf);
}

QByteArray sha256sum(const QByteArray& data)
{
    unsigned char output[32];
    sha256((unsigned char *)data.constData(), (size_t)data.size(), output, 0);
    return QByteArray((const char *)output, 32);
}

QByteArray sha1sum(const QByteArray& data)
{
    unsigned char output[20];
    sha1((unsigned char *)data.constData(), (size_t)data.size(), output);
    return QByteArray((const char *)output, 20);
}

QByteArray rsaSignSHA256Hash(const QByteArray& hash, pk_context *pk)
{
    int ret = 0;
    unsigned char sig[POLARSSL_MPI_MAX_SIZE];
    size_t sig_len;
    entropy_context entropy;
    ctr_drbg_context ctr_drbg;

    entropy_init(&entropy);

    QUuid uuid = QUuid::createUuid();
    QString personalString = QApplication::applicationName() + uuid.toString();
    QByteArray personalBa = personalString.toLocal8Bit();

    /*
    * Initialize random generator.
    * Personalisation string, does not need to be random but
    * should be unique according to documentation.
    *
    * the ctr_drbg structure does not need to be freed explicitly.
    */
    ret = ctr_drbg_init(&ctr_drbg, entropy_func, &entropy,
                        (const unsigned char*) personalBa.constData(),
                        personalBa.size());
    if (ret != 0) {
        qDebug() << "Failed to initialize drbg: " << getPolarSSLErrorMsg(ret);
        entropy_free (&entropy);
        return QByteArray();
    }

    ret = pk_sign(pk, POLARSSL_MD_SHA256, (const unsigned char*) hash.constData(),
                  hash.size(), sig, &sig_len, ctr_drbg_random, &ctr_drbg);
    entropy_free (&entropy);

    if (ret != 0) {
        qDebug() << "Failed to sign: " << getPolarSSLErrorMsg(ret);
        return QByteArray();
    }

    return QByteArray((const char *)sig, (int)sig_len);
}

http://wald.intevation.org/projects/trustbridge/