#include <WinSock2.h> #include <iostream> #include <string.h> #include <errno.h> #include <stdlib.h>
#include <openssl/bio.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <openssl/pem.h> #include <openssl/crypto.h>
extern "C" { #include <openssl/applink.c> }
#pragma comment(lib, "WS2_32.lib") #pragma comment(lib,"libssl.lib") #pragma comment(lib,"libcrypto.lib")
#define MAXBUF 1024
int main(int argc, char** argv) { SOCKET sockfd, new_fd; struct sockaddr_in socket_ptr, their_addr;
char buf[MAXBUF + 1] = {0};
SSL_CTX* ctx;
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
ctx = SSL_CTX_new(SSLv23_server_method()); if (ctx == NULL) { std::cout << "[-] 产生CTX上下文对象错误" << std::endl; return 0; } else { std::cout << "[+] 产生CTX上下文对象" << std::endl; }
if (SSL_CTX_use_certificate_file(ctx, "d://cacert.pem", SSL_FILETYPE_PEM) <= 0) { std::cout << "[-] 载入公钥失败" << std::endl; return 0; } else { std::cout << "[+] 已载入公钥" << std::endl; }
if (SSL_CTX_use_PrivateKey_file(ctx, "d://privkey.pem", SSL_FILETYPE_PEM) <= 0) { std::cout << "[-] 载入私钥失败" << std::endl; return 0; } else { std::cout << "[+] 已载入私钥" << std::endl; }
if (!SSL_CTX_check_private_key(ctx)) { std::cout << "[-] 用户私钥错误" << std::endl; return 0; }
WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) { WSACleanup(); return 0; }
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { return 0; }
socket_ptr.sin_family = AF_INET; socket_ptr.sin_addr.s_addr = htonl(INADDR_ANY); socket_ptr.sin_port = htons(9999);
if (bind(sockfd, (struct sockaddr*)&socket_ptr, sizeof(struct sockaddr)) == -1) { return 0; } if (listen(sockfd, 10) == -1) { return 0; }
while (1) { SSL* ssl; int len = sizeof(struct sockaddr);
if ((new_fd = accept(sockfd, (struct sockaddr*)&their_addr, &len)) != -1) { printf("客户端地址: %s --> 端口: %d --> 套接字: %d \n", inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port), new_fd); }
ssl = SSL_new(ctx);
SSL_set_fd(ssl, new_fd);
if (SSL_accept(ssl) == -1) { closesocket(new_fd); break; }
memset(buf, 0, MAXBUF); strcpy(buf, "[服务端消息] hello lyshark");
len = SSL_write(ssl, buf, strlen(buf)); if (len <= 0) { goto finish; return 0; }
memset(buf, 0, MAXBUF);
len = SSL_read(ssl, buf, MAXBUF); if (len > 0) { printf("[接收到客户端消息] => %s \n", buf); }
finish: SSL_shutdown(ssl); SSL_free(ssl); closesocket(new_fd); }
closesocket(sockfd); WSACleanup(); SSL_CTX_free(ctx);
system("pause"); return 0; }
|