19#ifdef ENABLE_CRYPTO_MBEDTLS
21#ifndef HEADER_CRYPTO_MBEDTLS_HPP
22#define HEADER_CRYPTO_MBEDTLS_HPP
24#include "utils/log.hpp"
27#include <mbedtls/ctr_drbg.h>
28#include <mbedtls/entropy.h>
29#include <mbedtls/gcm.h>
46 static std::string m_client_key;
48 static std::string m_client_iv;
50 std::array<uint8_t, 12> m_iv;
52 uint32_t m_packet_counter;
54 mbedtls_gcm_context m_aes_encrypt_context, m_aes_decrypt_context;
56 std::mutex m_crypto_mutex;
60 static std::string base64(
const std::vector<uint8_t>& input);
62 static std::vector<uint8_t> decode64(std::string input);
64 static std::array<uint8_t, 32>
sha256(
const std::string& input);
66 static std::unique_ptr<Crypto> getClientCrypto()
68 assert(!m_client_key.empty());
69 assert(!m_client_iv.empty());
70 auto c = std::unique_ptr<Crypto>(
new Crypto(decode64(m_client_key),
71 decode64(m_client_iv)));
72 c->m_packet_counter = 0;
76 static void initClientAES()
78 mbedtls_entropy_context entropy;
79 mbedtls_entropy_init(&entropy);
80 mbedtls_ctr_drbg_context ctr_drbg;
81 mbedtls_ctr_drbg_init(&ctr_drbg);
82 std::random_device rd;
84 std::array<uint8_t, 28> seed, key_iv;
85 for (
unsigned i = 0; i < 28; i++)
86 seed[i] = (uint8_t)(g() % 255);
88 if (mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
89 &entropy, seed.data(), seed.size()) == 0)
92 if (mbedtls_ctr_drbg_random((
void*)&ctr_drbg, key_iv.data(),
96 m_client_key = base64({ key_iv.begin(), key_iv.begin() + 16 });
97 m_client_iv = base64({ key_iv.begin() + 16, key_iv.end() });
100 static void resetClientAES()
106 static const std::string& getClientKey() {
return m_client_key; }
108 static const std::string& getClientIV() {
return m_client_iv; }
110 Crypto(
const std::vector<uint8_t>& key,
111 const std::vector<uint8_t>& iv)
113 assert(key.size() == 16);
114 assert(iv.size() == 12);
115 std::copy_n(iv.begin(), 12, m_iv.begin());
116 m_packet_counter = 0;
117 mbedtls_gcm_init(&m_aes_encrypt_context);
118 mbedtls_gcm_init(&m_aes_decrypt_context);
119 mbedtls_gcm_setkey(&m_aes_encrypt_context, MBEDTLS_CIPHER_ID_AES,
120 key.data(), key.size() * 8);
121 mbedtls_gcm_setkey(&m_aes_decrypt_context, MBEDTLS_CIPHER_ID_AES,
122 key.data(), key.size() * 8);
127 mbedtls_gcm_free(&m_aes_encrypt_context);
128 mbedtls_gcm_free(&m_aes_decrypt_context);
Describes a chain of 8-bit unsigned integers.
Definition: network_string.hpp:53
A new implementation of NetworkString, which has a fixed format: Byte 0: The type of the message,...
Definition: network_string.hpp:422
CScriptArray * sha256(std::string *input)
Return a sha256 checksum of string in an array of integers of size 32.
Definition: script_utils.cpp:164