aboutsummaryrefslogtreecommitdiff
path: root/lib/crypto/qolmutility.cpp
blob: bb50b4d07b541b3fbecee280877d9e76d891909a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// SPDX-FileCopyrightText: 2021 Carl Schwan <carlschwan@kde.org>
//
// SPDX-License-Identifier: LGPL-2.1-or-later

#include "crypto/qolmutility.h"
#include "olm/olm.h"
#include <QDebug>

using namespace Quotient;

// Convert olm error to enum
QOlmError lastError(OlmUtility *utility) {
    const std::string error_raw = olm_utility_last_error(utility);

    return fromString(error_raw);
}

QOlmUtility::QOlmUtility()
{
    auto utility = new uint8_t[olm_utility_size()];
    m_utility = olm_utility(utility);
}

QOlmUtility::~QOlmUtility()
{
    olm_clear_utility(m_utility);
    delete[](reinterpret_cast<uint8_t *>(m_utility));
}

QString QOlmUtility::sha256Bytes(const QByteArray &inputBuf) const
{
    const auto outputLen = olm_sha256_length(m_utility);
    QByteArray outputBuf(outputLen, '0');
    olm_sha256(m_utility, inputBuf.data(), inputBuf.length(),
            outputBuf.data(), outputBuf.length());

    return QString::fromUtf8(outputBuf);
}

QString QOlmUtility::sha256Utf8Msg(const QString &message) const
{
    return sha256Bytes(message.toUtf8());
}

std::variant<bool, QOlmError> QOlmUtility::ed25519Verify(const QByteArray &key,
        const QByteArray &message, const QByteArray &signature)
{
    QByteArray signatureBuf(signature.length(), '0');
    std::copy(signature.begin(), signature.end(), signatureBuf.begin());

    const auto ret = olm_ed25519_verify(m_utility, key.data(), key.size(),
            message.data(), message.size(), (void *)signatureBuf.data(), signatureBuf.size());

    const auto error = ret;
    if (error == olm_error()) {
        return lastError(m_utility);
    }

    if (ret != 0) {
        return false;
    }
    return true;
}