server
// sdf_cpp_warpper.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
// server端#ifndef UNICODE
#define UNICODE
#endif#define WIN32_LEAN_AND_MEAN#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>#include "sdf_warpper.hpp"
#include "cstring"#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib,"libhsm_core.lib")#define DEFAULT_BUFLEN 2048
using namespace std;typedef std::vector<unsigned char> bytes;
std::string BytesToStr(const bytes& in)
{bytes::const_iterator from = in.cbegin();bytes::const_iterator to = in.cend();std::ostringstream oss;for (; from != to; ++from)oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(*from);return oss.str();
}char hb2hex(unsigned char hb){hb = hb & 0xF;return hb < 10 ? '0' + hb : hb - 10 + 'a';
}string bytearray2hex(char byte_arr[], int arr_len)
{string res;for (size_t i = 0; i < arr_len; ++i) {res.push_back(hb2hex(byte_arr[i] >> 4));res.push_back(hb2hex(byte_arr[i]));}return res;
}void sm4_encrypt_decrypt_demo(char* outbuffer, int& out_buffer_true_length, char* decrypt_result, int& out_true_length) {sdf_qax::SDF_warpper sdf_warpper("{\"device_type\": \"rpc\",\"device_socket\": \"172.22.14.231:5000\"}");sdf_warpper.sm4_symmetry_decrypt((uint8_t*)sdf_warpper.getStaticKey(), outbuffer, out_buffer_true_length, decrypt_result, &out_true_length);}ECCCipher cipher; //密文存储结构体void sm2_encrypt_decrypt_demo() {sdf_qax::SDF_warpper sdf_warpper2("{\"device_type\": \"rpc\",\"device_socket\": \"172.22.14.231:5000\"}");char a[]{ '3','4','5' };std::cout << "input_data: ";for (char i : a) {std::cout << i;}std::cout << std::endl;sdf_warpper2.sm2_internal_encrypt(1, a, 3, &cipher);char decrypt_result[256]{ 0 };int out_true_length = 0;sdf_warpper2.sm2_internal_decrypt(1, &cipher, reinterpret_cast<sdf_uint8_t*>(decrypt_result), &out_true_length, nullptr, 0);std::cout << "Data length after decryption: " << out_true_length << std::endl;std::cout << "Data after decryption: ";for (int i = 0; i < out_true_length; i++) {std::cout << decrypt_result[i];}std::cout << std::endl;
}void main()
{//Initialze winsockWSADATA wsaData;if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0){std::cout << "Can't Initialize winsock!Quiting!" << std::endl;;return;}//Creste a sockrtSOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0);if (sockSrv == INVALID_SOCKET) {wprintf(L"Can't create a socket with error %d\n", WSAGetLastError());WSACleanup();return;}//Bind the socket to an ip address and portint port = 5099;SOCKADDR_IN addrSrv;addrSrv.sin_family = AF_INET;addrSrv.sin_port = htons(port); //1024以上的端口号addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//Bind the socketint retVal = bind(sockSrv, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));if (retVal == SOCKET_ERROR) {printf("Failed bind:%d\n", WSAGetLastError());closesocket(sockSrv);WSACleanup();return;}else {std::cout << "服务端成功开启" << std::endl;}//Tell winsock the socket is for listeningif (listen(sockSrv, SOMAXCONN) == SOCKET_ERROR) {printf("Listen failed:%d", WSAGetLastError());return;}//wait for a connectionSOCKADDR_IN addrClient;int clientSize = sizeof(addrClient);SOCKET sockConn = accept(sockSrv, (SOCKADDR*)&addrClient, &clientSize);if (sockConn == SOCKET_ERROR) {wprintf(L"accept failed with error: %ld\n", WSAGetLastError());closesocket(sockSrv);WSACleanup();return;}char host[NI_MAXHOST]; //Client's remote namechar service[NI_MAXSERV]; //Service (i.e. port)the client is connect onZeroMemory(host, NI_MAXHOST);//Same as memset(host,0,NI_MAXHOST)ZeroMemory(service, NI_MAXSERV);if (getnameinfo((sockaddr*)&addrClient, sizeof(addrClient), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0) {std::cout << "客户端建立连接使用的端口号是 " << service << std::endl;}else {inet_ntop(AF_INET, &addrClient.sin_addr, host, NI_MAXHOST);std::cout << host << " connect on port " << ntohs(addrClient.sin_port) << std::endl;}//while loop:accept and echo message back to clientchar recvbuf[DEFAULT_BUFLEN] = "";int recvbuflen = DEFAULT_BUFLEN;memset(recvbuf, 0, sizeof(recvbuf));char sendbuf[] = "此数据来自服务端,连接建立成功!\n";retVal = send(sockConn, sendbuf, sizeof(sendbuf), 0);if (retVal == SOCKET_ERROR) {wprintf(L"send failed with error: %d\n", WSAGetLastError());closesocket(sockSrv);WSACleanup();return;}do {retVal = recv(sockConn, recvbuf, recvbuflen, 0);if (retVal > 0) {char decrypt_result[64]{ 0 };int out_true_length = 0;//printf("接收到的密文数据的字节数: %ld\n", retVal);string input_2(recvbuf, recvbuf + retVal);clock_t start, end;start = clock(); //开始时间sm4_encrypt_decrypt_demo(recvbuf, retVal, decrypt_result, out_true_length);end = clock(); //结束时间string return_value = bytearray2hex(recvbuf, retVal);printf("接收到的密文16进制表示: ");std::cout << return_value << std::endl;std::cout << "服务端解密密文用时: " << double(end - start) / CLOCKS_PER_SEC << "s" << endl; //输出时间(单位:s)printf("解密后明文指令: %s\n", decrypt_result);std::cout << std::endl;}else if (retVal == 0)printf("客户端不再传输数据,连接关闭!\n");elsewprintf(L"recv failed with error: %d\n", WSAGetLastError());} while (retVal > 0);closesocket(sockConn);//close socketclosesocket(sockSrv);//close winsockWSACleanup();system("pause");
}
client
// sdf_cpp_warpper.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
// client端#ifndef UNICODE
#define UNICODE
#endif#define WIN32_LEAN_AND_MEAN#include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
#include <winsock2.h>
#include <Ws2tcpip.h>#include "sdf_warpper.hpp"
#include "cstring"#pragma comment(lib,"libhsm_core.lib")
#pragma comment(lib, "Ws2_32.lib")
using namespace std;typedef std::vector<unsigned char> bytes;
std::string BytesToStr(const bytes& in)
{bytes::const_iterator from = in.cbegin();bytes::const_iterator to = in.cend();std::ostringstream oss;for (; from != to; ++from)oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(*from);return oss.str();
}void sm4_encrypt_decrypt_demo(const char* input_data,int length,char* outbuffer,int & out_buffer_true_length) {sdf_qax::SDF_warpper sdf_warpper("{\"device_type\": \"rpc\",\"device_socket\": \"172.22.14.231:5000\"}");char a[32]{};memcpy(a, input_data,length);std::cout << "待加密的明文指令: ";for (auto i : a) {std::cout << i;} bytes input(a, a + 24);sdf_warpper.sm4_symmetry_encrypt((uint8_t*)sdf_warpper.getStaticKey(), a, sizeof(a) / sizeof(char), outbuffer, &out_buffer_true_length);bytes input_2(outbuffer, outbuffer + out_buffer_true_length);std::cout << std::endl; std::cout << "密文16进制表示: ";std::cout << BytesToStr(input_2) << std::endl;char decrypt_result[32]{ 0 };int out_true_length = 0;sdf_warpper.sm4_symmetry_decrypt((uint8_t*)sdf_warpper.getStaticKey(), outbuffer, out_buffer_true_length, decrypt_result, &out_true_length);
}
ECCCipher cipher; //密文存储结构体void sm2_encrypt_decrypt_demo() {sdf_qax::SDF_warpper sdf_warpper2("{\"device_type\": \"rpc\",\"device_socket\": \"172.22.14.231:5000\"}"); char a[]{ '3','4','5' };std::cout << "input_data: ";for (char i : a) {std::cout << i;}std::cout << std::endl;sdf_warpper2.sm2_internal_encrypt(1, a, 3, &cipher);char decrypt_result[256]{ 0 };int out_true_length = 0;sdf_warpper2.sm2_internal_decrypt(1, &cipher, reinterpret_cast<sdf_uint8_t *>(decrypt_result), &out_true_length, nullptr, 0);std::cout << "Data length after decryption: " << out_true_length << std::endl;std::cout << "Data after decryption: ";for (int i = 0; i < out_true_length; i++) {std::cout << decrypt_result[i];}std::cout << std::endl;
}void main() {//Initialze winsockWSADATA wsaData;if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0){std::cout << "Can't Initialize winsock!Quiting!" << std::endl;;return;}//Creste a sockrtSOCKET sockClient = socket(AF_INET, SOCK_STREAM, 0);if (sockClient == INVALID_SOCKET) {wprintf(L"Can't create a socket with error %d\n", WSAGetLastError());WSACleanup();return;}//Bind the socket to an ip address and portint port = 5099;SOCKADDR_IN addrSrv;addrSrv.sin_family = AF_INET;addrSrv.sin_port = htons(5099);//addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");inet_pton(AF_INET, "127.0.0.1", &addrSrv.sin_addr.S_un.S_addr);char buff[1024];memset(buff, 0, sizeof(buff));//向服务器发出连接请求if (connect(sockClient, (struct sockaddr*) & addrSrv, sizeof(addrSrv)) == INVALID_SOCKET) {printf("Connect failed:%d", WSAGetLastError());return;}else{//接收数据recv(sockClient, buff, sizeof(buff), 0);printf("%s", buff);}char input_vec[][24] = { { '0','0','0','0','0','0','0','0','0','0','0','6','0','1','0','3','0','0','0','E','0','0','0','2'},{ '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', 'B', '0', '1', '0', '6', '0', '0', '1', '3', '0', '0', '0', 'A'},{ '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '6', '0', '1', '0', '5', '0', '3', '3', '5', 'F', 'F', '0', '0' } ,{ '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '6', '0', '1', '0', '5', '0', '3', '3', '6', 'F', 'F', '0', '0' } };for (int i = 0;i < 4;i++) {char outbuffer[32]{ 0 };int out_buffer_true_length = 0;clock_t start, end;start = clock(); //开始时间sm4_encrypt_decrypt_demo(input_vec[i], 24, outbuffer, out_buffer_true_length);end = clock(); //结束时间std::cout << "加密数据用时: " << double(end - start) / CLOCKS_PER_SEC << "s" << endl; //输出时间(单位:s)char sendbuf[2048];ZeroMemory(sendbuf, 2048);strcpy_s(sendbuf, outbuffer);if (send(sockClient, sendbuf, out_buffer_true_length, 0) == SOCKET_ERROR) {wprintf(L"send failed with error: %d\n", WSAGetLastError());closesocket(sockClient);WSACleanup();exit(-1);}std::cout << std::endl;}//关闭套接字closesocket(sockClient);WSACleanup();system("pause");
}