diff --git a/CMakeLists.txt b/CMakeLists.txt index 39864fd..9c6aa19 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.15) +cmake_minimum_required(VERSION 3.13) project(Net) set(CMAKE_CXX_STANDARD 14) @@ -6,30 +6,13 @@ set(CMAKE_CXX_STANDARD 14) include_directories(include/) include_directories(utils/) -find_package(Boost REQUIRED) -find_package(OpenSSL REQUIRED) - -message(STATUS SSL ${OPENSSL_LIBRARIES}) - -include(GoogleTest) - -set(OPENSSL_LIBS /usr/local/lib/libssl.dylib /usr/local/lib/libcrypto.dylib) -set(GTEST_LIB /usr/local/lib/) -set(GTEST_LIBS gtest pthread dl) +find_package(Boost REQUIRED thread) +find_package(OpenSSL 1.1.1 REQUIRED) include_directories(${Boost_INCLUDE_DIRS} ${OPENSSL_INCLUDE_DIR} ${SQLiteCpp_INCLUDE_DIRS}) -link_directories(${GTEST_LIB}) -aux_source_directory(src SOURCE_ALL) +enable_testing() -add_executable(NetTest test/test_main.cpp) +add_subdirectory(src) -gtest_add_tests(TARGET NetTest - TEST_SUFFIX .noArgs - TEST_LIST noArgsTests) - -add_library(m_error STATIC src/error.cpp) -add_library(m_rsa STATIC src/rsa_cpp_binding.cpp) - -target_link_libraries(NetTest m_rsa m_error ${GTEST_LIBS} ssl crypto boost_program_options) -set_tests_properties(${noArgsTests} PROPERTIES TIMEOUT 10) \ No newline at end of file +add_subdirectory(test) \ No newline at end of file diff --git a/include/cmap.h b/include/cmap.h index 9307956..53a8bee 100644 --- a/include/cmap.h +++ b/include/cmap.h @@ -11,7 +11,7 @@ #include "type.h" #include "cpart.h" -#include "sha256_cpp_binding.h" +#include "util/sha256_generator.h" #include "sql.h" //计算模块管理对象间的依赖关系管理结构 diff --git a/include/communicate/tcp_client.h b/include/communicate/tcp_client.h new file mode 100644 index 0000000..f081424 --- /dev/null +++ b/include/communicate/tcp_client.h @@ -0,0 +1,45 @@ +// +// Created by 胡宇 on 2020/7/9. +// + +#ifndef NET_TCP_CLIENT_H +#define NET_TCP_CLIENT_H + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace Net { + + class TCPClient { + public: + TCPClient(const std::string &ip, int port); + + int sendData(const std::string &data); + + + private: + int fd{}; + struct sockaddr_in client_addr{}; + + std::stringstream recv_buff; + + void create_socket_and_connection(); + + void recv_cycle(); + + static void recv_data(TCPClient *client); + }; + +} + + +#endif //NET_TCP_CLIENT_H diff --git a/include/communicate/tcp_server.h b/include/communicate/tcp_server.h new file mode 100644 index 0000000..90288bd --- /dev/null +++ b/include/communicate/tcp_server.h @@ -0,0 +1,62 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#ifndef NET_TCP_SERVER_H +#define NET_TCP_SERVER_H + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + + +namespace Net { + + class TCPServer { + public: + TCPServer(int port, int max_connection); + + ~TCPServer(){ + stop(); + close(fd); + } + + void stop(){ + if(p_accept_manager_thread != nullptr) + p_accept_manager_thread->interrupt(); + this->status = -1; + } + + uint8_t readByte(); + + private: + int fd; + int status = 0; + struct sockaddr_in server_addr; + std::queue recv_buff; + boost::mutex buff_mutex; + boost::thread *p_accept_manager_thread; + + void cycle(); + + static void accept_manager(TCPServer *server); + + static void accept(int fd, boost::mutex *buff_mutex, std::queue *recv_buff, const int *status); + + void create_socket(int port); + }; + +} + +#endif //NET_TCP_SERVER_H diff --git a/include/cproj.h b/include/cproj.h index 949b1cc..fce1c8a 100644 --- a/include/cproj.h +++ b/include/cproj.h @@ -11,7 +11,7 @@ #include "type.h" #include "cpart.h" -#include "sha256_cpp_binding.h" +#include "util/sha256_generator.h" #include "sql.h" class Proj; diff --git a/include/debug_tools/print_tools.h b/include/debug_tools/print_tools.h new file mode 100644 index 0000000..11e154f --- /dev/null +++ b/include/debug_tools/print_tools.h @@ -0,0 +1,37 @@ +// +// Created by Eric Saturn on 2019/12/12. +// + +#ifndef NET_PRINT_TOOLS_H +#define NET_PRINT_TOOLS_H + +#include +#include + +using std::string; +using std::initializer_list; +using std::pair; + +//提示信息打印类函数 +namespace Net { + + namespace PrintTools { + + using FormalItem = pair; + + void debugPrintError(const string &error_info); + + void debugPrintWarning(const string &warning_info); + + void debugPrintSuccess(const string &success_info); + + void printInfo(const string& info, const string& tag); + + void printInfoBuffer(const string& info, const string& tag); + + void printInfoFormal(const string& title, initializer_list body); + } +} + + +#endif //NET_PRINT_TOOLS_H diff --git a/include/error.h b/include/error.h deleted file mode 100644 index d20088d..0000000 --- a/include/error.h +++ /dev/null @@ -1,38 +0,0 @@ -// -// Created by Eric Saturn on 2019/12/12. -// - -#ifndef NET_ERROR_H -#define NET_ERROR_H - -#include -#include - -using std::string; -using std::initializer_list; -using std::pair; - -//提示信息打印类函数 -namespace Net { - namespace error { - - using FormalItem = pair; - - void printError(string error_info); - - void printWarning(string warning_info); - - void printSuccess(string succes_info); - - void printRed(string red_info); - - void printInfo(const string& info, string tag = ""); - - void printInfoBuffer(const string& info, string tag = ""); - - void printInfoFormal(const string& title, initializer_list body); - } -} - - -#endif //NET_ERROR_H diff --git a/include/sha256_cpp_binding.h b/include/sha256_cpp_binding.h deleted file mode 100644 index e3bb3ff..0000000 --- a/include/sha256_cpp_binding.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -using std::string; -using std::ifstream; -using std::stringstream; - -class SHA256Generator{ -public: - SHA256Generator(string data){ - this->raw_data = std::move(data); - } - - SHA256Generator(ifstream stream){ - while(stream.good()){ - stream >> raw_data; - } - stream.close(); - } - - void generate(); - - string getHex(){ - if(!if_generate) generate(); - return this->sha256_data; - } -private: - bool if_generate = false; - string raw_data; - string sha256_data; -}; diff --git a/include/type.h b/include/type.h index 4f95d2f..7876a01 100644 --- a/include/type.h +++ b/include/type.h @@ -51,8 +51,6 @@ #include #include -#include - using std::string; using std::vector; diff --git a/include/utils/aes_cbc_encryptor.h b/include/utils/aes_cbc_encryptor.h new file mode 100644 index 0000000..8eb1a3b --- /dev/null +++ b/include/utils/aes_cbc_encryptor.h @@ -0,0 +1,47 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#ifndef NET_AES_CBC_ENCRYPTOR_H +#define NET_AES_CBC_ENCRYPTOR_H + +#include +#include +#include +#include +#include + +#include "debug_tools/print_tools.h" +#include "random_generator.h" + +namespace Net { + + class AESCBCEncryptor { + public: + + AESCBCEncryptor(); + + string getKeyData() const; + + void encrypt(const std::string &data, std::string &encrypted_data); + + void decrypt(std::string &data, const std::string &encrypt_data); + + private: + const int nrounds = 8; + + uint8_t key[32], iv[32]; + + EVP_CIPHER_CTX *e_ctx = EVP_CIPHER_CTX_new(); + + std::string key_data; + + void generate_random_key_data(); + + void aes_init(std::string &key_data); + + }; + +} + +#endif //NET_AES_CBC_ENCRYPTOR_H diff --git a/include/utils/random_generator.h b/include/utils/random_generator.h new file mode 100644 index 0000000..e18ff84 --- /dev/null +++ b/include/utils/random_generator.h @@ -0,0 +1,30 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#ifndef NET_RANDOM_GENERATOR_H +#define NET_RANDOM_GENERATOR_H + +#include +#include + +namespace Net{ + namespace Rand{ + +// 范围均匀分布无符号32位整数 + class UniformUInt { + public: + UniformUInt(uint32_t min, uint32_t max) : uniformInt(min, max){ + + } + + int generate() const; + private: + boost::uniform_int uniformInt; + }; + + } +} + + +#endif //NET_RANDOM_GENERATOR_H diff --git a/include/rsa_cpp_binding.h b/include/utils/rsa_key_chain.h similarity index 86% rename from include/rsa_cpp_binding.h rename to include/utils/rsa_key_chain.h index 97a179f..5cdbe8d 100644 --- a/include/rsa_cpp_binding.h +++ b/include/utils/rsa_key_chain.h @@ -2,11 +2,11 @@ // Created by Eric Saturn on 2019/12/10. // -#ifndef NET_RSA_CPP_BINDING_H -#define NET_RSA_CPP_BINDING_H +#ifndef NET_RSA_KEY_CHAIN_H +#define NET_RSA_KEY_CHAIN_H -#include "error.h" -#include "../src/bignumber.cpp" +#include "debug_tools/print_tools.h" +#include "../../src/bignumber.cpp" #include #include @@ -18,6 +18,10 @@ using namespace std; namespace Net { + + /** + * The Public Key For A RSA Key Chain + */ class RSAPubKey{ public: explicit RSAPubKey(const RSA *rsa){ @@ -29,7 +33,7 @@ namespace Net { } void printInfo(){ - error::printInfoFormal("RSAPubKey Info", { + PrintTools::printInfoFormal("RSAPubKey Info", { {"n", this->n.getDataHex()}, {"e", this->e.getDataHex()} }); @@ -39,6 +43,9 @@ namespace Net { BigNumber e; }; + /** + * The Private Key For A RSA Key Chain + */ class RSAPrvKey{ public: explicit RSAPrvKey(const RSA *rsa) { @@ -54,8 +61,8 @@ namespace Net { this->q.copyFrom(q); } - void printInfo(){ - error::printInfoFormal("RSAPrvKey Info", { + void printInfo() const{ + PrintTools::printInfoFormal("RSAPrvKey Info", { {"n", this->n.getDataHex()}, {"e", this->e.getDataHex()}, {"d", this->d.getDataHex()}, @@ -95,13 +102,16 @@ namespace Net { this->if_prv_key = true; } +// 生成一对公私钥 void generateKeyPair(); // 检查私钥是否合法 bool checkKey(); +// 公钥加密 void publicKeyEncrypt(const string &data, string &encrypted_data); +// 私钥解密 void privateKeyDecrypt(string &data, const string& encrypted_data); uint32_t getBufferSize() const { @@ -134,4 +144,4 @@ namespace Net { } -#endif //NET_RSA_CPP_BINDING_H +#endif //NET_RSA_KEY_CHAIN_H diff --git a/include/utils/sha256_generator.h b/include/utils/sha256_generator.h new file mode 100644 index 0000000..ac988c0 --- /dev/null +++ b/include/utils/sha256_generator.h @@ -0,0 +1,36 @@ +#pragma once + +#include +#include +#include +#include + +using std::string; +using std::ifstream; +using std::stringstream; + +namespace Net { + +/** + * The Generator of SHA256 Hex + * We can use it in an easy way. + */ + class SHA256Generator { + public: + SHA256Generator(string data); + + SHA256Generator(ifstream stream); + + void replace(string &str); + + void generate(); + + string getHex(); + + private: + bool if_generate = false; + string raw_data; + string sha256_data; + }; + +} \ No newline at end of file diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..f508e42 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,3 @@ +add_subdirectory(utils) +add_subdirectory(debug_tools) +add_subdirectory(communicate) \ No newline at end of file diff --git a/src/communicate/CMakeLists.txt b/src/communicate/CMakeLists.txt new file mode 100644 index 0000000..aa67340 --- /dev/null +++ b/src/communicate/CMakeLists.txt @@ -0,0 +1,3 @@ +file(GLOB commuSrc *.cpp) + +add_library(commu STATIC ${commuSrc}) \ No newline at end of file diff --git a/src/communicate/tcp_client.cpp b/src/communicate/tcp_client.cpp new file mode 100644 index 0000000..2f2053d --- /dev/null +++ b/src/communicate/tcp_client.cpp @@ -0,0 +1,41 @@ +// +// Created by 胡宇 on 2020/7/9. +// + +#include "communicate/tcp_client.h" + +void Net::TCPClient::recv_data(Net::TCPClient *client) { + u_char buff[1024]; + int len; + while ((len = recv(client->fd, buff, sizeof(buff), 0)) > 0) { + client->recv_buff.write(reinterpret_cast(buff), len); + } +} + +void Net::TCPClient::recv_cycle() { + boost::thread recv_thread(TCPClient::recv_data, + this); + recv_thread.detach(); +} + +void Net::TCPClient::create_socket_and_connection() { + if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { + throw std::runtime_error("create socket failed."); + } + connect(fd, (struct sockaddr *) &client_addr, sizeof(client_addr)); +} + +int Net::TCPClient::sendData(const std::string &data) { + create_socket_and_connection(); + recv_cycle(); + int len = send(fd, data.data(), data.size(), 0); + close(fd); + return len; +} + +Net::TCPClient::TCPClient(const std::string &ip, int port) { + std::memset(&client_addr, 0, sizeof(client_addr)); + client_addr.sin_family = AF_INET; + client_addr.sin_addr.s_addr = inet_addr(ip.c_str()); + client_addr.sin_port = htons(port); +} diff --git a/src/communicate/tcp_server.cpp b/src/communicate/tcp_server.cpp new file mode 100644 index 0000000..578fe72 --- /dev/null +++ b/src/communicate/tcp_server.cpp @@ -0,0 +1,80 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#include "debug_tools/print_tools.h" +#include "communicate/tcp_server.h" + +void Net::TCPServer::cycle() { + boost::thread accept_manager_thread(TCPServer::accept_manager, this); + this->p_accept_manager_thread = &accept_manager_thread; + accept_manager_thread.detach(); +} + +void Net::TCPServer::accept_manager(Net::TCPServer *server) { + Net::PrintTools::debugPrintSuccess("AcceptManager Started."); + while(true){ + int connect_fd = ::accept(server->fd, nullptr, nullptr); + Net::PrintTools::debugPrintSuccess("New Connection."); + + if(connect_fd == -1) throw std::runtime_error("accept tcp connection error"); + else{ + boost::thread accept_thread(TCPServer::accept, connect_fd, &server->buff_mutex, &server->recv_buff, &server->status); + accept_thread.detach(); + } + } +} + +void Net::TCPServer::accept(int fd, boost::mutex *buff_mutex, std::queue *recv_buff, const int *status) { + Net::PrintTools::debugPrintSuccess("Try Getting Data From Connection."); + uint8_t buff[1024]; + int len; + std::vector accept_buff; + while((len = recv(fd, buff, sizeof(buff), 0)) > 0 && *status == 0){ + Net::PrintTools::debugPrintSuccess("Received."); + for(int i = 0; i < len; ++i) accept_buff.push_back(buff[i]); + } + if(*status == 0) { + buff_mutex->lock(); + for(unsigned char & i : accept_buff) + recv_buff->push(i); + buff_mutex->unlock(); + } + close(fd); + Net::PrintTools::debugPrintSuccess("Connection Closed."); +} + +void Net::TCPServer::create_socket(int port) { + fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if(!~fd) throw std::runtime_error("could not create socket file."); + + std::memset(&server_addr, 0, sizeof(struct sockaddr_in)); + server_addr.sin_family = AF_INET; + server_addr.sin_addr.s_addr = htonl(INADDR_ANY); + server_addr.sin_port = htons(port); +} + +Net::TCPServer::TCPServer(int port, int max_connection) { + + create_socket(port); + + if(bind(fd, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1) + throw std::runtime_error("bind port failed."); + + if(listen(fd, max_connection) == -1) + throw std::runtime_error("listen socket failed."); + + + cycle(); +} + +uint8_t Net::TCPServer::readByte() { + uint8_t byte = '\0'; + buff_mutex.try_lock(); + if(!recv_buff.empty()) { + byte = recv_buff.front(); + recv_buff.pop(); + } + buff_mutex.unlock(); + return byte; +} diff --git a/src/debug_tools/CMakeLists.txt b/src/debug_tools/CMakeLists.txt new file mode 100644 index 0000000..7c1e1a5 --- /dev/null +++ b/src/debug_tools/CMakeLists.txt @@ -0,0 +1 @@ +add_library(debugTools STATIC print_tools.cpp) \ No newline at end of file diff --git a/src/error.cpp b/src/debug_tools/print_tools.cpp similarity index 63% rename from src/error.cpp rename to src/debug_tools/print_tools.cpp index d6ba7f1..dc46784 100644 --- a/src/error.cpp +++ b/src/debug_tools/print_tools.cpp @@ -2,48 +2,44 @@ // Created by Eric Saturn on 2019/12/12. // -#include "error.h" +#include "debug_tools/print_tools.h" using std::string; namespace Net { - namespace error { - void printError(string error_info) { + namespace PrintTools { + void debugPrintError(const string &error_info) { printf("\033[31mError: %s\033[0m\n", error_info.data()); } - void printWarning(string warning_info) { + void debugPrintWarning(const string &warning_info) { printf("\033[33mWarning: %s\033[0m\n", warning_info.data()); } - void printSuccess(string succes_info) { - printf("\033[32m%s\033[0m\n", succes_info.data()); + void debugPrintSuccess(const string &success_info) { + printf("\033[32m%s\033[0m\n", success_info.data()); } - void printRed(string red_info) { - printf("\033[31m%s\n\033[0m", red_info.data()); - } - - void printInfo(const string& info, string tag) { + void printInfo(const string& info, const string& tag) { printf("[DEBUG INFO] %s ", info.data()); - if(tag.size()) + if(!tag.empty()) printf("{ %s }\n",tag.data()); } void printInfoFormal(const string& title, initializer_list body) { printf("\n>>>\n {%s}\n",title.data()); printf(">-------------------------------------\n"); - for(auto item : body){ + for(auto &item : body){ printf("[%s] : \"%s\"; \n", item.first.data(), item.second.data()); } printf("----------------------------------<\n<<<\n\n"); } - void printInfoBuffer(const string &info, string tag) { + void printInfoBuffer(const string &info, const string& tag) { printf("\n[DEBUG INFO (BUFFER)]\n"); printf(">----------------------------------------------\n"); - uint8_t *p_i = (uint8_t *) &info[0]; - uint8_t *p_e = (uint8_t *) &info[info.size()-1]; + auto *p_i = (uint8_t *) &info[0]; + auto *p_e = (uint8_t *) &info[info.size()-1]; for(int c = 0;p_i < p_e; ++p_i, ++c){ if(!(c % 16) && c) printf("\n"); printf("%02x ",*p_i); @@ -51,7 +47,7 @@ namespace Net { } printf("\n"); printf("----------------------------------------------<\n"); - if(tag.size()) + if(!tag.empty()) printf("{ %s }\n\n",tag.data()); } } diff --git a/src/sha256_cpp_binding.cpp b/src/sha256_cpp_binding.cpp deleted file mode 100644 index bfc5301..0000000 --- a/src/sha256_cpp_binding.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include "type.h" -#include "sha256_cpp_binding.h" - -void SHA256Generator::generate() { - unsigned char hash[SHA256_DIGEST_LENGTH]; - SHA256_CTX sha256; - SHA256_Init(&sha256); - SHA256_Update(&sha256, raw_data.c_str(), raw_data.size()); - SHA256_Final(hash, &sha256); - stringstream buffer; - char buf[2]; - for(int i = 0; i < SHA256_DIGEST_LENGTH; ++i){ - sprintf(buf,"%02x",hash[i]); - buffer << buf; - } - sha256_data = buffer.str(); - if_generate = true; -} diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt new file mode 100644 index 0000000..d327464 --- /dev/null +++ b/src/utils/CMakeLists.txt @@ -0,0 +1,3 @@ +file(GLOB utilSrc *.cpp) + +add_library(utils STATIC ${utilSrc}) diff --git a/src/utils/aes_cbc_encryptor.cpp b/src/utils/aes_cbc_encryptor.cpp new file mode 100644 index 0000000..33c06e9 --- /dev/null +++ b/src/utils/aes_cbc_encryptor.cpp @@ -0,0 +1,77 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#include "utils/aes_cbc_encryptor.h" + + +void Net::AESCBCEncryptor::encrypt(const string &data, string &encrypted_data) { + int c_len = data.length() + AES_BLOCK_SIZE, f_len = 0; + + auto *encrypt_buffer = reinterpret_cast(malloc(c_len)); + + EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), nullptr, key, iv); + EVP_EncryptUpdate(e_ctx, encrypt_buffer, &c_len, + reinterpret_cast(data.data()), data.length()); + EVP_EncryptFinal_ex(e_ctx, encrypt_buffer + c_len, &f_len); + + int len = c_len + f_len; + + if(!encrypted_data.empty()) encrypted_data.clear(); + + encrypted_data.append(reinterpret_cast(encrypt_buffer), len); + + EVP_CIPHER_CTX_reset(e_ctx); +} + +void Net::AESCBCEncryptor::decrypt(string &data, const string &encrypt_data) { + int p_len = encrypt_data.length(), f_len = 0; + auto *plain_buffer = static_cast(malloc(p_len)); + + EVP_DecryptInit_ex(e_ctx, EVP_aes_256_cbc(), nullptr, key, iv); + EVP_DecryptUpdate(e_ctx, plain_buffer, &p_len, + reinterpret_cast(encrypt_data.data()), encrypt_data.length()); + EVP_DecryptFinal_ex(e_ctx, plain_buffer + p_len, &f_len); + + int len = p_len + f_len; + + if(!data.empty()) data.clear(); + + data.append(reinterpret_cast(plain_buffer), len); + + EVP_CIPHER_CTX_reset(e_ctx); +} + +void Net::AESCBCEncryptor::generate_random_key_data() { + Rand::UniformUInt rand(0, UINT32_MAX); + + uint32_t p_data[8]; + for(unsigned int & i : p_data){ + i = rand.generate(); + } + + key_data.append(reinterpret_cast(p_data), 32); +} + +void Net::AESCBCEncryptor::aes_init(string &key_data) { + + + int i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha256(), nullptr, + reinterpret_cast(key_data.c_str()), key_data.length(), + nrounds, key, iv); + if (i != 32) { + throw std::runtime_error("key data must equal 256 bits."); + } + + EVP_CIPHER_CTX_init(e_ctx); + EVP_EncryptInit_ex(e_ctx, EVP_aes_256_cbc(), nullptr, key, iv); +} + +string Net::AESCBCEncryptor::getKeyData() const { + return key_data; +} + +Net::AESCBCEncryptor::AESCBCEncryptor() { + generate_random_key_data(); + aes_init(key_data); +} diff --git a/src/utils/random_generator.cpp b/src/utils/random_generator.cpp new file mode 100644 index 0000000..81d2d5b --- /dev/null +++ b/src/utils/random_generator.cpp @@ -0,0 +1,11 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#include "utils/random_generator.h" + +boost::random::mt19937 rand_seed; + +int Net::Rand::UniformUInt::generate() const { + return uniformInt(rand_seed); +} diff --git a/src/rsa_cpp_binding.cpp b/src/utils/rsa_key_chain.cpp similarity index 85% rename from src/rsa_cpp_binding.cpp rename to src/utils/rsa_key_chain.cpp index 6a9b774..a11d80a 100644 --- a/src/rsa_cpp_binding.cpp +++ b/src/utils/rsa_key_chain.cpp @@ -2,7 +2,10 @@ // Created by Eric Saturn on 2019/12/10. // -#include "rsa_cpp_binding.h" +#include +#include "utils/rsa_key_chain.h" + +using std::runtime_error; void Net::RSAKeyChain::generateKeyPair() { BigNumber e; @@ -21,13 +24,12 @@ void Net::RSAKeyChain::privateKeyDecrypt(string &data, const string &encrypted_d if(this->key_pair == nullptr) throw runtime_error("key pair is invalid"); if(encrypted_data.size() != buffer_size) throw runtime_error("encrypt data's size is abnormal"); // 使用私钥解密 - int decrypted_size = -1; unique_ptrp_buffer (new unsigned char[buffer_size]); - if((decrypted_size = RSA_private_decrypt(encrypted_data.size(), + if(RSA_private_decrypt(encrypted_data.size(), reinterpret_cast(&encrypted_data[0]), p_buffer.get(), key_pair, - RSA_PKCS1_OAEP_PADDING)) == -1) + RSA_PKCS1_OAEP_PADDING) == -1) throw runtime_error(ERR_error_string(ERR_get_error(), nullptr)); else data = string(reinterpret_cast(p_buffer.get())); } @@ -43,12 +45,11 @@ void Net::RSAKeyChain::publicKeyEncrypt(const string &data, string &encrypted_da string tmp_data = data; tmp_data.resize(buffer_size - 42); // 使用公钥加密 - int encrypted_size = -1; - if((encrypted_size = RSA_public_encrypt(tmp_data.size(), + if(RSA_public_encrypt(tmp_data.size(), reinterpret_cast(&tmp_data[0]), reinterpret_cast(&encrypted_data[0]), key_pair, - RSA_PKCS1_OAEP_PADDING)) == -1) + RSA_PKCS1_OAEP_PADDING) == -1) throw runtime_error(ERR_error_string(ERR_get_error(), nullptr)); } @@ -56,6 +57,6 @@ bool Net::RSAKeyChain::checkKey() { if(!this->if_prv_key) throw runtime_error("illegal call of checkKey"); if(this->key_pair == nullptr) throw runtime_error("key pair is invalid"); int return_code = RSA_check_key(this->key_pair); - if(return_code == -1) throw runtime_error("error occur when rsa check key"); + if(return_code == -1) throw runtime_error("PrintTools occur when rsa check key"); else return return_code == 1; } diff --git a/src/utils/sha256_generator.cpp b/src/utils/sha256_generator.cpp new file mode 100644 index 0000000..09d3d91 --- /dev/null +++ b/src/utils/sha256_generator.cpp @@ -0,0 +1,41 @@ +#include "type.h" +#include "utils/sha256_generator.h" + +/** + * Generate SHA256 Hex Code + */ +void Net::SHA256Generator::generate() { + unsigned char hash[SHA256_DIGEST_LENGTH]; + SHA256_CTX sha256; + SHA256_Init(&sha256); + SHA256_Update(&sha256, raw_data.c_str(), raw_data.size()); + SHA256_Final(hash, &sha256); + stringstream buffer; + char buf[2]; + for(int i = 0; i < SHA256_DIGEST_LENGTH; ++i){ + sprintf(buf,"%02x",hash[i]); + buffer << buf; + } + sha256_data = buffer.str(); + if_generate = true; +} + +void Net::SHA256Generator::replace(string &str) { + this->raw_data = str; +} + +string Net::SHA256Generator::getHex() { + if (!if_generate) generate(); + return this->sha256_data; +} + +Net::SHA256Generator::SHA256Generator(ifstream stream) { + while (stream.good()) { + stream >> raw_data; + } + stream.close(); +} + +Net::SHA256Generator::SHA256Generator(string data) { + this->raw_data = std::move(data); +} diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt new file mode 100644 index 0000000..adb5254 --- /dev/null +++ b/test/CMakeLists.txt @@ -0,0 +1,9 @@ +find_package(GTest REQUIRED) + +set(GTEST_LIB /usr/local/lib/) +set(GTEST_LIBS gtest gmock pthread dl) + +link_directories(${GTEST_LIB}) + +add_subdirectory(test_util) +add_subdirectory(test_commu) diff --git a/test/env.h b/test/env.h index fd39229..d2f2d1c 100644 --- a/test/env.h +++ b/test/env.h @@ -5,7 +5,7 @@ #ifndef NET_ENV_H #define NET_ENV_H -#include "rsa_cpp_binding.h" +#include "utils/rsa_key_chain.h" class GlobalTestEnv : public testing::Environment{ public: diff --git a/test/rsa_test.cpp b/test/rsa_test.cpp deleted file mode 100644 index 1ae60bd..0000000 --- a/test/rsa_test.cpp +++ /dev/null @@ -1,52 +0,0 @@ -// -// Created by Eric Saturn on 2019/12/12. -// - -#include -#include - -#include "env.h" - -using namespace Net; -using namespace std; - -extern GlobalTestEnv *_env; - -TEST(RSATest, init_test_1) { - -} - -TEST(RSATest, generate_test_1) { - _env->rsa->generateKeyPair(); - error::printInfo(to_string(_env->rsa->getBufferSize()), string("Buffer Size")); -} - -TEST(RSATest, pub_encrypt_test_1) { - string encrypted_data; - _env->rsa->publicKeyEncrypt(_env->rsa_test_data, encrypted_data); - error::printInfoBuffer(encrypted_data, "Encrypted Data"); - _env->rsa_encrypt_data = encrypted_data; -} - -TEST(RSATest, prv_decrypt_test_1){ - string data; - _env->rsa->privateKeyDecrypt(data, _env->rsa_encrypt_data); - error::printInfo(data, "Decrypt Data"); - ASSERT_EQ(data, _env->rsa_test_data); -} - -TEST(RSATest, pub_key_get_test_1){ - _env->pubKey = shared_ptr(new RSAPubKey(_env->rsa->getRSA())); - -} - -TEST(RSATest, prv_key_get_test_1){ - _env->prvKey = shared_ptr(new RSAPrvKey(_env->rsa->getRSA())); - ASSERT_EQ(_env->rsa->checkKey(), true); - _env->prvKey->printInfo(); -} - -TEST(RSATest, prv_key_build_key_chain){ - RSAKeyChain keyChain(*_env->prvKey); - ASSERT_EQ(keyChain.checkKey(), true); -} \ No newline at end of file diff --git a/test/test_commu/CMakeLists.txt b/test/test_commu/CMakeLists.txt new file mode 100644 index 0000000..0634114 --- /dev/null +++ b/test/test_commu/CMakeLists.txt @@ -0,0 +1,9 @@ + +file(GLOB testSrc *.cpp) + +add_compile_definitions(DEBUG) + +add_executable(testCommu ${testSrc}) + +target_link_libraries(testCommu commu debugTools Boost::thread) + diff --git a/test/test_commu/main.cpp b/test/test_commu/main.cpp new file mode 100644 index 0000000..1d83182 --- /dev/null +++ b/test/test_commu/main.cpp @@ -0,0 +1,31 @@ +// +// Created by 胡宇 on 2020/7/9. +// + +#include +#include + +#include "debug_tools/print_tools.h" +#include "communicate/tcp_server.h" +#include "communicate/tcp_client.h" + +using namespace Net; + +int main(int argc, char *argv[]){ + if(fork() == 0) { + PrintTools::debugPrintSuccess("Child Started."); + TCPClient client("127.0.0.1", 9048); + for(int i = 0; i < 32; i++, usleep(1e4)) + client.sendData("Hello"); + PrintTools::debugPrintSuccess("Child Exited."); + } + else{ + PrintTools::debugPrintSuccess("Father Started."); + TCPServer server(9048, 100); + while (true){ + std::putchar(server.readByte()); + usleep(1e3); + } + } + return 0; +} \ No newline at end of file diff --git a/test/test_util/CMakeLists.txt b/test/test_util/CMakeLists.txt new file mode 100644 index 0000000..ffda1a7 --- /dev/null +++ b/test/test_util/CMakeLists.txt @@ -0,0 +1,11 @@ + +file(GLOB testSrc *.cpp) + +add_executable(testUtils ${testSrc}) + +message(${GTEST_LIBS}) + +target_link_libraries(testUtils utils debugTools ssl crypto ${GTEST_LIBS}) + +add_test(Name testUtils + COMMAND testUtils) \ No newline at end of file diff --git a/test/test_main.cpp b/test/test_util/main.cpp similarity index 53% rename from test/test_main.cpp rename to test/test_util/main.cpp index 39098e8..d9a0cf1 100644 --- a/test/test_main.cpp +++ b/test/test_util/main.cpp @@ -4,14 +4,12 @@ #include -#include "rsa_test.cpp" +#include "../env.h" -#include "env.h" - -GlobalTestEnv *_env; +GlobalTestEnv *env; int main(int argc, char *argv[]){ ::testing::InitGoogleTest(&argc, argv); - _env = dynamic_cast(::testing::AddGlobalTestEnvironment(new GlobalTestEnv)); + env = dynamic_cast(::testing::AddGlobalTestEnvironment(new GlobalTestEnv)); return RUN_ALL_TESTS(); } diff --git a/test/test_util/test_aes.cpp b/test/test_util/test_aes.cpp new file mode 100644 index 0000000..8c3ff64 --- /dev/null +++ b/test/test_util/test_aes.cpp @@ -0,0 +1,25 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#include + +#include "utils/aes_cbc_encryptor.h" + +using namespace Net; + +TEST(AES_Test, base_test_1){ + AESCBCEncryptor encryptor; + + PrintTools::printInfoBuffer(encryptor.getKeyData(), "Key Data"); + + std::string data, encrypt_data; + + encryptor.encrypt("Hello World", encrypt_data); + + PrintTools::printInfoBuffer(encrypt_data, "Encrypt Data"); + + encryptor.decrypt(data, encrypt_data); + + ASSERT_EQ(data, std::string("Hello World")); +} \ No newline at end of file diff --git a/test/test_util/test_rsa.cpp b/test/test_util/test_rsa.cpp new file mode 100644 index 0000000..ff8131d --- /dev/null +++ b/test/test_util/test_rsa.cpp @@ -0,0 +1,56 @@ +// +// Created by Eric Saturn on 2019/12/12. +// + +#include + +#include + +#include "../env.h" + +#include "utils/rsa_key_chain.h" + +using namespace Net; +using namespace std; + +extern GlobalTestEnv *env; + +TEST(RSATest, init_test_1) { + +} + +TEST(RSATest, generate_test_1) { + env->rsa->generateKeyPair(); + string data = std::to_string(env->rsa->getBufferSize()); + PrintTools::printInfo(data, "Buffer Size"); +} + +TEST(RSATest, pub_encrypt_test_1) { + string encrypted_data; + env->rsa->publicKeyEncrypt(env->rsa_test_data, encrypted_data); + PrintTools::printInfoBuffer(encrypted_data, "Encrypted Data"); + env->rsa_encrypt_data = encrypted_data; +} + +TEST(RSATest, prv_decrypt_test_1){ + string data; + env->rsa->privateKeyDecrypt(data, env->rsa_encrypt_data); + PrintTools::printInfo(data, "Decrypt Data"); + ASSERT_EQ(data, env->rsa_test_data); +} + +TEST(RSATest, pub_key_get_test_1){ + env->pubKey = std::make_shared(env->rsa->getRSA()); + +} + +TEST(RSATest, prv_key_get_test_1){ + env->prvKey = std::make_shared(env->rsa->getRSA()); + ASSERT_EQ(env->rsa->checkKey(), true); + env->prvKey->printInfo(); +} + +TEST(RSATest, prv_key_build_key_chain){ + RSAKeyChain keyChain(*env->prvKey); + ASSERT_EQ(keyChain.checkKey(), true); +} \ No newline at end of file diff --git a/test/test_util/test_sha.cpp b/test/test_util/test_sha.cpp new file mode 100644 index 0000000..b213fe6 --- /dev/null +++ b/test/test_util/test_sha.cpp @@ -0,0 +1,20 @@ +// +// Created by 胡宇 on 2020/7/7. +// + +#include + +#include "utils/sha256_generator.h" +#include "debug_tools/print_tools.h" + +using namespace Net; + +TEST(SHA256Test, base_test_1){ + SHA256Generator generator("Hello World."); + generator.generate(); + + PrintTools::printInfo(generator.getHex(), "SHA256 Hex"); + + ASSERT_EQ(generator.getHex(), + std::string("f4bb1975bf1f81f76ce824f7536c1e101a8060a632a52289d530a6f600d52c92")); +} \ No newline at end of file