Welcome to mirror list, hosted at ThFree Co, Russian Federation.

GcryptMPI.cpp « fdosecrets « src - github.com/keepassxreboot/keepassxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4fc792debaf30fccb088ea6b0cf48568a71872d9 (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
/*
 *  Copyright (C) 2019 Aetf <aetf@unlimitedcodeworks.xyz>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 or (at your option)
 *  version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "GcryptMPI.h"

GcryptMPI MpiFromBytes(const QByteArray& bytes, bool secure, gcry_mpi_format format)
{
    auto bufLen = static_cast<size_t>(bytes.size());

    const char* buf = nullptr;

    // gcry_mpi_scan uses secure memory only if input buffer is secure memory, so we have to make a copy
    GcryptMemPtr secureBuf;
    if (secure) {
        secureBuf.reset(static_cast<char*>(gcry_malloc_secure(bufLen)));
        memcpy(secureBuf.get(), bytes.data(), bufLen);
        buf = secureBuf.get();
    } else {
        buf = bytes.data();
    }

    gcry_mpi_t rawMpi;
    auto err = gcry_mpi_scan(&rawMpi, format, buf, format == GCRYMPI_FMT_HEX ? 0 : bufLen, nullptr);
    GcryptMPI mpi(rawMpi);

    if (gcry_err_code(err) != GPG_ERR_NO_ERROR) {
        mpi.reset();
    }

    return mpi;
}

GcryptMPI MpiFromHex(const char* hex, bool secure)
{
    return MpiFromBytes(QByteArray::fromRawData(hex, static_cast<int>(strlen(hex) + 1)), secure, GCRYMPI_FMT_HEX);
}

QByteArray MpiToBytes(const GcryptMPI& mpi)
{
    unsigned char* buf = nullptr;
    size_t buflen = 0;
    gcry_mpi_aprint(GCRYMPI_FMT_USG, &buf, &buflen, mpi.get());

    QByteArray bytes(reinterpret_cast<char*>(buf), static_cast<int>(buflen));

    gcry_free(buf);

    return bytes;
}