| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | // Copyright 2019 Juan Palacios <[email protected]> |
| 3 | |
| 4 | #include "cryptolayer.h" |
| 5 | |
| 6 | #include <botan/base64.h> |
| 7 | #include <botan/data_src.h> |
| 8 | #include <botan/ed25519.h> |
| 9 | #include <botan/pubkey.h> |
| 10 | #include <botan/system_rng.h> |
| 11 | #include <botan/x509_key.h> |
| 12 | #include <cstddef> |
| 13 | #include <cstdint> |
| 14 | #include <exception> |
| 15 | #include <spdlog/spdlog.h> |
| 16 | |
| 17 | void CryptoLayer::init() |
| 18 | { |
| 19 | privateKey_ = std::make_unique<Botan::Ed25519_PrivateKey>(Botan::system_rng()); |
| 20 | } |
| 21 | |
| 22 | QByteArray CryptoLayer::publicKey() |
| 23 | { |
| 24 | auto key = Botan::X509::PEM_encode(*privateKey_); |
| 25 | return {key.c_str()}; |
| 26 | } |
| 27 | |
| 28 | void CryptoLayer::usePublicKey(QByteArray const &publicKey) |
| 29 | { |
| 30 | auto keyStr = publicKey.toStdString(); |
| 31 | Botan::DataSource_Memory pubKey(keyStr); |
| 32 | opPublicKey_ = |
| 33 | std::unique_ptr<Botan::Public_Key>(Botan::X509::load_key(pubKey)); |
| 34 | } |
| 35 | |
| 36 | bool CryptoLayer::verify(QByteArray const &data, QByteArray const &signature) |
| 37 | { |
| 38 | try { |
| 39 | Botan::PK_Verifier verifier(*opPublicKey_, "SHA-512"); |
| 40 | auto decodedSignature = Botan::base64_decode(signature.toStdString()); |
| 41 | return verifier.verify_message( |
| 42 | reinterpret_cast<uint8_t const *>(data.data()), |
| 43 | static_cast<size_t>(data.size()), decodedSignature.data(), |
| 44 | decodedSignature.size()); |
| 45 | } |
| 46 | catch (std::exception const &e) { |
| 47 | SPDLOG_DEBUG(e.what()); |
| 48 | } |
| 49 | return false; |
| 50 | } |
| 51 | |
| 52 | QByteArray CryptoLayer::signature(QByteArray const &data) |
| 53 | { |
| 54 | try { |
| 55 | Botan::PK_Signer signer(*privateKey_, Botan::system_rng(), "SHA-512"); |
| 56 | auto signature = signer.sign_message( |
| 57 | reinterpret_cast<uint8_t const *>(data.data()), |
| 58 | static_cast<size_t>(data.size()), Botan::system_rng()); |
| 59 | auto encodedSignature = Botan::base64_encode(signature); |
| 60 | return {encodedSignature.c_str()}; |
| 61 | } |
| 62 | catch (std::exception const &e) { |
| 63 | SPDLOG_DEBUG(e.what()); |
| 64 | } |
| 65 | return {}; |
| 66 | } |