#include <iostream> #include <winsock2.h> #include <WS2tcpip.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/aes.h> #include <openssl/crypto.h>
extern "C" { #include <openssl/applink.c> }
#pragma comment(lib,"ws2_32.lib") #pragma comment(lib,"libssl_static.lib") #pragma comment(lib,"libcrypto.lib")
void AES(unsigned char* InBuff, unsigned char* OutBuff, unsigned char* key, char* Type) { if (strcmp(Type, "encode") == 0) { AES_KEY AESEncryptKey; AES_set_encrypt_key(key, 256, &AESEncryptKey); AES_encrypt(InBuff, OutBuff, &AESEncryptKey); } else if (strcmp(Type, "decode") == 0) { AES_KEY AESDecryptKey; AES_set_decrypt_key(key, 256, &AESDecryptKey); AES_decrypt(InBuff, OutBuff, &AESDecryptKey); } }
int main(int argc, char* argv[]) { WSADATA WSAData; WSAStartup(MAKEWORD(2, 0), &WSAData);
SOCKET server_socket; server_socket = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in ServerAddr; ServerAddr.sin_family = AF_INET; ServerAddr.sin_port = htons(9999); ServerAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
bind(server_socket, (LPSOCKADDR)&ServerAddr, sizeof(ServerAddr)); listen(server_socket, 10);
SOCKET message_socket; if ((message_socket = accept(server_socket, (LPSOCKADDR)0, (int*)0)) != INVALID_SOCKET) { unsigned char aes_key[32] = { 0x11,0x22,0x33,0x44 };
char* encrypt = nullptr; int encrypt_length = 0;
unsigned char Buffer[1024] = {0}; unsigned char DecodeBuf[1024] = { 0 };
recv(message_socket, (char *)Buffer, 1024, 0); std::cout << "接收加密长度: " << strlen((char *)Buffer) << std::endl;
AES(Buffer, DecodeBuf, aes_key, (char*)"decode"); std::cout << "解密内容: " << DecodeBuf << std::endl;
} closesocket(server_socket); WSACleanup(); system("pause"); return 0; }
|