I wrote simple C programs, which are using sockets ('client' and 'server'). (UNIX/Linux usage)
The server side simply creates a socket:
sockfd = socket(AF_INET, SOCK_STREAM, 0);
And then binds it to sockaddr:
bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
And listens (and accepts and reads):
listen(sockfd,5);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
read(newsockfd,buffer,255);
The client creates the socket, and then writes to it.
Now, I want to convert this simple connection into an SSL connection, in the plainest, most idyllic, neatest and quickest way.
I've tried to add OpenSSL to my project, but I can't find an easy way to implement what I want.
OpenSSL is quite difficult. It's easy to accidentally throw away all your security by not doing negotiation exactly right. (Heck, I've been personally bitten by a bug where curl wasn't reading the OpenSSL alerts exactly right, and couldn't talk to some sites.)
If you really want quick and simple, put stud in front of your program an call it a day. Having SSL in a different process won't slow you down: http://vincent.bernat.im/en/blog/2011-ssl-benchmark.html
There are several steps when using OpenSSL. You must have an SSL certificate made which can contain the certificate with the private key be sure to specify the exact location of the certificate (this example has it in the root). There are a lot of good tutorials out there.
Some includes:
You will need to initialize OpenSSL:
Now for the bulk of the functionality. You may want to add a while loop on connections.
You are then able read or write using:
Update The
SSL_CTX_new
should be called with the TLS method that best fits your needs in order to support the newer versions of security, instead ofSSLv23_server_method()
. See: OpenSSL SSL_CTX_new descriptionFor others like me:
If you download the SSL source, there's a directory
demos/ssl/
with example code in c++: https://github.com/openssl/openssl/tree/master/demos/sslUPDATE: they have removed that demo. Now it's available only via the history: https://github.com/openssl/openssl/tree/691064c47fd6a7d11189df00a0d1b94d8051cbe0/demos/ssl You probably will have to find a working version, I originally posted this answer at Nov 6 2015. And I had to edit the source -- not much.
Certificates: .pem in
demos/certs/apps/
: https://github.com/openssl/openssl/tree/master/demos/certs/appsHere my example ssl socket server threads (multiple connection) https://github.com/breakermind/CppLinux/blob/master/QtSslServerThreads/breakermindsslserver.cpp