19#ifdef ENABLE_CRYPTO_OPENSSL
21#ifndef HEADER_CRYPTO_OPENSSL_HPP
22#define HEADER_CRYPTO_OPENSSL_HPP
24#include "utils/log.hpp"
28#define OPENSSL_API_COMPAT 0x09800000L
29#include <openssl/evp.h>
30#include <openssl/rand.h>
47 static std::string m_client_key;
49 static std::string m_client_iv;
51 std::array<uint8_t, 12> m_iv;
53 uint32_t m_packet_counter;
55 EVP_CIPHER_CTX* m_encrypt;
57 EVP_CIPHER_CTX* m_decrypt;
59 std::mutex m_crypto_mutex;
62 static size_t calcDecodeLength(
const std::string& input)
66 const size_t len = input.
size();
67 if (input[len - 1] ==
'=' && input[len - 2] ==
'=')
72 else if (input[len - 1] ==
'=')
77 return (len * 3) / 4 - padding;
81 static std::string base64(
const std::vector<uint8_t>& input);
83 static std::vector<uint8_t> decode64(std::string input);
85 static std::array<uint8_t, 32>
sha256(
const std::string& input);
87 static std::unique_ptr<Crypto> getClientCrypto()
89 assert(!m_client_key.empty());
90 assert(!m_client_iv.empty());
91 auto c = std::unique_ptr<Crypto>(
new Crypto(decode64(m_client_key),
92 decode64(m_client_iv)));
93 c->m_packet_counter = 0;
97 static void initClientAES()
99 std::random_device rd;
100 std::mt19937 g(rd());
103 std::vector<uint8_t> key;
104 for (
int i = 0; i < 16; i++)
105 key.push_back((uint8_t)(g() % 255));
106 std::vector<uint8_t> iv;
107 for (
int i = 0; i < 12; i++)
108 iv.push_back((uint8_t)(g() % 255));
109 if (!RAND_bytes(key.data(), 16))
112 "Failed to generate cryptographically strong key");
114 m_client_key = base64(key);
115 m_client_iv = base64(iv);
118 static void resetClientAES()
124 static const std::string& getClientKey() {
return m_client_key; }
126 static const std::string& getClientIV() {
return m_client_iv; }
128 Crypto(
const std::vector<uint8_t>& key,
129 const std::vector<uint8_t>& iv)
131 assert(key.size() == 16);
132 assert(iv.size() == 12);
133 std::copy_n(iv.begin(), 12, m_iv.begin());
134 m_packet_counter = 0;
135 m_encrypt = EVP_CIPHER_CTX_new();
136 EVP_CIPHER_CTX_init(m_encrypt);
137 EVP_EncryptInit_ex(m_encrypt, EVP_aes_128_gcm(), NULL, key.data(),
139 m_decrypt = EVP_CIPHER_CTX_new();
140 EVP_CIPHER_CTX_init(m_decrypt);
141 EVP_DecryptInit_ex(m_decrypt, EVP_aes_128_gcm(), NULL, key.data(),
147 EVP_CIPHER_CTX_free(m_encrypt);
148 EVP_CIPHER_CTX_free(m_decrypt);
Describes a chain of 8-bit unsigned integers.
Definition: network_string.hpp:53
unsigned int size() const
Returns the remaining length of the network string.
Definition: network_string.hpp:191
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