[Network programming] Win32 Socket + OpenSSL instance

Source: Internet
Author: User
Tags openssl library ssl connection htons
OpenSSL

OpenSSL is not just SSL. It can implement message digest, file encryption and decryption, digital certificates, digital signatures and random numbers. There are a lot of content about the OpenSSL library, which is far from an article.

OpenSSL is not just an API, but also a command line tool. The command line tool can do the same work as the API, and further test the SSL server and client.

Server coding process source code: Create a win32 Empty Project SSL_Server
// SSL_Server.cpp # include <iostream> # include <winsock2.h> # include <openssl/rsa. h>/* SSLeay stuff */# include <openssl/crypto. h> # include <openssl/x509.h> # include <openssl/pem. h> # include <openssl/ssl. h> # include <openssl/err. h> // # privatekey. pem // cmd :.. \ openssl-1.0.1e \ bin> openssl genrsa-out privatekey. pem 2048 -- an empty password is generated // # cacert. pem // cmd :.. \ openssl-1.0.1e \ bin> openssl req-new-x509-key private Key. pem-out cacert. pem-days 1095-config .. \ ssl \ openssl. cnf # define CACERT "E: \ ReferData \ OpenSSL \ openssl-1.0.1e \ bin \ cacert. pem "# define PRIKEY" E: \ ReferData \ OpenSSL \ openssl-1.0.1e \ bin \ privatekey. pem "# define PRIKEY_CODE" women123 "// ---- be consistent with the generated key # define MAXBUF 1024 # define DEFPORT 7838 # pragma comment (lib," ws2_32.lib ") # pragma comment (lib, lib, "libeay32.lib") # pragma comment (lib, "ssleay3 2. lib ") ************************ * ********************* filename: ssl-server.c * purpose: demonstrate how to use the OpenSSL library for IP layer-based SSL encrypted communication, this is a server-side example * wrote by: zhoulifa (zhoulifa@163.com) Weekly release (http://zhoulifa.bokee.com) linux enthusiast Linux knowledge transmitter sohou developers are best at C Language * date time: * Note: Anyone can copy code and use these documents at will, of course, it includes your commercial use * but follow GPL * Thanks to: Google * Hope: more and more people are expected to contribute their own strength, contribute to the development of science and technology * technological progress is faster on the shoulders of giants! Thank you for your contributions to the open source team! **************************************** * ***************************/Int main () {int sockfd, new_fd; int len; struct sockaddr_in my_addr, their_addr; char buf [MAXBUF + 1]; SSL_CTX * ctx; SSL_library_init (); /* initialize the SSL library */OpenSSL_add_all_algorithms ();/* load all SSL algorithms */SSL_load_error_strings (); /* load all SSL error messages */ctx = SSL_CTX_new (SSLv23_server_method ();/* generate an SSL_CTX in the standard SSL V2 and V3 compatibility mode, that is, SSL C Ontent Text * // * You can also use SSLv2_server_method () or SSLv3_server_method () to separately represent V2 or V3 standard */if (ctx = NULL) {ERR_print_errors_fp (stdout ); exit (1);} if (SSL_CTX_use_certificate_file (ctx, CACERT, SSL_FILETYPE_PEM) <= 0)/* load your digital certificate, which is sent to the client. The certificate contains the Public Key */{ERR_print_errors_fp (stdout); exit (1);} // SSL_CTX_set_default_passwd_cb_userdata (ctx, PRIKEY_CODE); // if it is not an empty private file, without this line of code, "EnterPEM pess phrass:" will appear --- enter the password if (SSL_CTX_use_PrivateKey_file (ctx, PRIKEY, SSL_FILETYPE_PEM) <= 0) /* load the user's private key */{ERR_print_errors_fp (stdout); exit (1);} if (! SSL_CTX_check_private_key (ctx)/* check whether the user's private key is correct */{ERR_print_errors_fp (stdout); exit (1);} WSADATA wsaData; int ret = WSAStartup (MAKEWORD (2, 2), & wsaData); if (ret! = 0) {std: cout <"WSAStartup error. "<std: endl; return-1;}/* enable a socket listener */if (sockfd = socket (PF_INET, SOCK_STREAM, 0) =-1) {perror ("socket"); exit (1);} else printf ("socket created \ n"); memset (& my_addr, 0, sizeof (my_addr )); my_addr.sin_family = PF_INET; my_addr.sin_port = htons (DEFPORT); region = INADDR_ANY; if (bind (sockfd, (struct sockaddr *) & my_addr, sizeof (struct) Sockaddr) =-1) {perror ("bind"); exit (1);} else printf ("binded \ n"); if (listen (sockfd, 2) =-1) {perror ("listen"); exit (1);} else printf ("begin listen \ n"); while (1) {SSL * ssl; len = sizeof (struct sockaddr);/* Wait for the client to connect */if (new_fd = accept (sockfd, (struct sockaddr *) & their_addr, & len )) =-1) {perror ("accept"); exit (errno);} else printf ("server: got connection from % s, port % d, socket % D \ n ", inet_ntoa (secure), ntohs (their_addr.sin_port), new_fd); ssl = SSL_new (ctx);/* generate a new SSL */SSL_set_fd (ssl, new_fd);/* Add the socket of the connected user to SSL */if (SSL_accept (ssl) =-1) /* establish an SSL connection */{perror ("accept"); closesocket (new_fd); break;}/* start to process the data sending and receiving of each new connection */memset (buf, 0, MAXBUF + 1); strcpy (buf, "server-> client");/* send a message to the client */len = SSL_write (ssl, buf, strlen (buf )); if (le N <= 0) {printf ("message '% s' failed to be sent! Error code: % d, error message: '% s' \ n ", buf, errno, strerror (errno); goto finish ;} else printf ("message '% s' is successfully sent. % d bytes are sent in total! \ N ", buf, len); memset (buf, 0, MAXBUF + 1);/* receive client messages */len = SSL_read (ssl, buf, MAXBUF ); if (len> 0) printf ("Message received successfully: '% s', % d bytes of data \ n", buf, len ); else printf ("message receiving failed! Error code: % d, error message: '% s' \ n ", errno, strerror (errno); finish: /* process the data sent and received by each new connection */SSL_shutdown (ssl);/* close the SSL connection */SSL_free (ssl);/* release SSL */closesocket (new_fd ); /* close socket */} closesocket (sockfd);/* close the socket */SSL_CTX_free (ctx);/* release CTX */return 0 ;}
Client coding process source code: Create a win32 Empty Project SSL_Client
// SSL_Client.cpp # include <iostream> # include <winsock2.h> # include <openssl/rsa. h>/* SSLeay stuff */# include <openssl/crypto. h> # include <openssl/x509.h> # include <openssl/pem. h> # include <openssl/ssl. h> # include <openssl/err. h> # pragma comment (lib, "ws2_32.lib") # pragma comment (lib, "libeay32.lib") # pragma comment (lib, "ssleay32.lib ") # define MAXBUF 1024 # define DEF_IP "127.0.0.1" # define DEF_PORT 78 38 void ShowCerts (SSL * ssl) {X509 * cert; char * line; cert = SSL_get_peer_certificate (ssl); if (cert! = NULL) {printf ("Digital Certificate Information: \ n"); line = X509_NAME_oneline (X509_get_subject_name (cert), 0, 0); printf ("certificate: % s \ n ", line); OPENSSL_free (line); line = X509_NAME_oneline (X509_get_issuer_name (cert), 0, 0); printf (" issuer: % s \ n ", line); OPENSSL_free (line); X509_free (cert);} else printf ("no certificate information! \ N ");} ************************ * ********************* filename: ssl-client.c * purpose: demonstrate how to use the OpenSSL library for IP layer-based SSL encrypted communication, this is a client example * wrote by: zhoulifa (zhoulifa@163.com) Weekly release (http://zhoulifa.bokee.com) linux enthusiast Linux knowledge transmitter sohou developers are best at C Language * date time: * Note: Anyone can copy code and use these documents at will, of course, it includes your commercial use * but follow GPL * Thanks to: Google * Hope: more and more people are expected to contribute their own strength, contribute to the development of science and technology * technological progress is faster on the shoulders of giants! Thank you for your contributions to the open source team! **************************************** * ***************************/Int main () {int sockfd, len; struct sockaddr_in dest; char buffer [MAXBUF + 1]; SSL_CTX * ctx; SSL * ssl;/* SSL library initialization, see the ssl-server.c Code */SSL_library_init (); sums (); SSL_load_error_strings (); ctx = SSL_CTX_new (SSLv23_client_method (); if (ctx = NULL) {sums (stdout ); exit (1);} WSADATA wsaData; I Nt ret = WSAStartup (MAKEWORD (2, 2), & wsaData); if (ret! = 0) {std: cout <"WSAStartup error. "<std: endl; return-1;}/* Create a socket for tcp communication */if (sockfd = socket (AF_INET, SOCK_STREAM, 0) <0) {perror ("Socket"); exit (errno);} printf ("socket created \ n");/* initialize the server (PEER) /memset (& dest, 0, sizeof (dest); dest. sin_family = AF_INET; dest. sin_addr.S_un.S_addr = inet_addr (DEF_IP); dest. sin_port = htons (DEF_PORT); printf ("address created \ n");/* connection Server */if (connect (sockfd, (struct sockaddr *) & dest, sizeof (dest ))! = 0) {perror ("Connect"); exit (errno);} printf ("server connected \ n "); /* generate a new SSL */ssl = SSL_new (ctx) based on ctx; SSL_set_fd (ssl, sockfd);/* establish an SSL connection */if (SSL_connect (ssl) =-1) ERR_print_errors_fp (stderr); else {printf ("Connected with % s encryption \ n", SSL_get_cipher (ssl); ShowCerts (ssl );} /* receive messages sent from the other party. A maximum of MAXBUF bytes */memset (buffer, 0, MAXBUF + 1) can be received ); /* receive messages from the server */len = SSL_read (ssl, B Uffer, MAXBUF); if (len> 0) printf ("Message received successfully: '% s', % d bytes of data \ n", buffer, len ); else {printf ("message receiving failed! Error code: % d, error message: '% s' \ n ", errno, strerror (errno); goto finish;} memset (buffer, 0, MAXBUF + 1 ); strcpy (buffer, "from client-> server");/* send a message to the server */len = SSL_write (ssl, buffer, strlen (buffer); if (len <0) printf ("message '% s' failed to be sent! Error code: % d, error message: '% s' \ n ", buffer, errno, strerror (errno); else printf (" message' % s' is sent successfully, % d bytes are sent! \ N ", buffer, len); finish:/* close connection */SSL_shutdown (ssl); SSL_free (ssl); closesocket (sockfd); SSL_CTX_free (ctx ); system ("pause"); return 0 ;}

Refer to blog:

Linux Network Programming step by step-encrypted communication protocol SSL research using key digital certificate OpenSSL in openssl System

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.