File indexing completed on 2025-02-16 04:50:54

0001 /*
0002  * SPDX-FileCopyrightText: 2021 Volker Krause <vkrause@kde.org>
0003  * SPDX-License-Identifier: LGPL-2.0-or-later
0004  */
0005 
0006 #include "nlbase45_p.h"
0007 
0008 #include "openssl/bignum_p.h"
0009 #include "openssl/opensslpp_p.h"
0010 
0011 #include <QByteArray>
0012 #include <QDebug>
0013 
0014 #include <algorithm>
0015 
0016 static constexpr const char nlBase45Table[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
0017 
0018 static int8_t nlBase45MapFromChar(char c)
0019 {
0020     const auto it = std::find(std::begin(nlBase45Table), std::end(nlBase45Table), c);
0021     if (it == std::end(nlBase45Table)) {
0022         qWarning() << "invalid base45 character:" << c;
0023         return -1;
0024     }
0025     return std::distance(std::begin(nlBase45Table), it);
0026 }
0027 
0028 QByteArray NLBase45::decode(const char *begin, const char *end)
0029 {
0030     openssl::bn_ptr bn(BN_new());
0031     BN_zero(bn.get());
0032     for (auto it = begin; it != end; ++it) {
0033         BN_mul_word(bn.get(), 45);
0034         auto v = nlBase45MapFromChar(*it);
0035         if (v < 0) {
0036             break;
0037         }
0038         BN_add_word(bn.get(), v);
0039     }
0040     return Bignum::toByteArray(bn);
0041 }