VC ++ network security programming example (11)-SSL advanced encryption Network Communication

Source: Internet
Author: User
Tags openssl library ssl connection

SSL (Secure Sockets Layer) and its successor Transport Layer Security (TLS) are a Security protocol that provides Security and data integrity for network communication. TLS and SSL encrypt network connections at the transport layer.

SSL (Secure Socket Layer) is developed by Netscape to ensure the security of data transmission over the Internet, it ensures that data is not intercepted or eavesdropped during network transmission. At present, the general specification is 40 bits, while the United States has released a 128 bits higher security standard, but the exit is restricted. Only the I. E. or Netscape Browser later than version 3.0 supports SSL. The current version is 3.0. It has been widely used for identity authentication and encrypted data transmission between Web browsers and servers.

The SSL protocol is located between the TCP/IP protocol and various application layer protocols to provide security support for data communication. The SSL Protocol can be divided into two layers: SSL Record Protocol (SSL Record Protocol): it is built on a reliable transmission Protocol (such as TCP, provides data encapsulation, compression, encryption, and other basic functions for high-level protocols. SSL Handshake Protocol: It is built on the SSL record Protocol and used before the actual data transmission starts, both parties perform identity authentication, negotiate encryption algorithms, and exchange encryption keys.

SSL provides the following services:

1) authenticate users and servers to ensure that data is sent to the correct client and server;

2) encrypt data to prevent data theft;

3) maintain data integrity and ensure that data is not changed during transmission.

SSL protocol workflow:

Server Authentication phase:

1) the client sends a start message "Hello" to the server to start a new session connection;

2) The server determines whether to generate a new CMK based on the customer's information. If necessary, the server will include the information required to generate the CMK in response to the customer's "Hello" information;

3) The customer generates a master key based on the server response information and encrypts it with the public key of the server before sending it to the server;

4) The server restores the CMK and returns a message for the customer to authenticate the server with the CMK.

User authentication stage: before that, the server has passed the customer authentication, which completes the customer authentication. The authenticated server sends a question to the customer, and the customer returns the question signed by (number) and the Public Key to provide the server with authentication.

From the services provided by the SSL protocol and their workflow, we can see that the foundation of the SSL protocol is the merchant's commitment to the confidentiality of consumer information, which is conducive to the merchant and is not conducive to the consumer. In the early stage of e-commerce, most enterprises that operate e-commerce are large companies with high reputation, so this problem has not been fully exposed. However, with the development of e-commerce, various small and medium enterprises are also involved, which leads to the problem of single authentication in the electronic payment process becoming more and more prominent. Although SSL3.0 uses digital signatures and digital certificates to verify the identity of both the browser and the Web server, the SSL protocol still has some problems, such, the SSL protocol can only provide mutual authentication between the client and the server in the transaction. In electronic transactions involving multiple parties, the secure transmission and trust relationship between the parties cannot be coordinated. In this case, the two credit card organizations, Visa and MasterCard, have developed a SET agreement to provide global standards for online credit card payment.

Let's implement SSL network communication in person

The client code implementation is as follows:

 

# Include "commonlib. h "</p> <p> # define CAFILE DATA_DIR" \ rootcert. pem "<br/> # define cadir null <br/> # define CLNTCERT DATA_DIR" \ client. pem "</p> <p> SSL_CTX * setup_client_ctx (void) <br/> {<br/> // generate a context object that supports SSL2.0 or SSL3.0 <br/> SSL_CTX * ctx = SSL_CTX_new (SSLv23_method ()); <br/> // load certificate path <br/> if (SSL_CTX_load_verify_locations (ctx, CAFILE, CADIR )! = 1) <br/> int_error ("An error occurred while loading the CA file"); <br/> // set the default certificate verification path <br/> if (SSL_CTX_set_default_verify_paths (ctx )! = 1) <br/> int_error ("An error occurred while loading the default CA file "); </p> <p> // load the Client Private Key Certificate <br/> if (SSL_CTX_use_certificate_chain_file (ctx, CLNTCERT )! = 1) <br/> int_error ("An error occurred while loading the client certificate file"); <br/> // read the client private key, you need to provide a password for this private key. <br/> if (SSL_CTX_use_PrivateKey_file (ctx, CLNTCERT, SSL_FILETYPE_PEM )! = 1) <br/> int_error ("An error occurred while loading the private key from the client certificate file"); </p> <p> // It is set to verify the Peer (server) certificate <br/> SSL_CTX_set_verify (ctx, SSL_VERIFY_PEER, verify_callback); <br/> // set the maximum path length for verification <br/> SSL_CTX_set_verify_depth (ctx, 4 ); <br/> return ctx; <br/>}</p> <p> int do_client_task (SSL * ssl) <br/>{< br/> int outlen; <br/> int leftlen; <br/> char buf [80]; <br/> printf ("enter a string to the server: \ n "); <br/> if (! Fgets (buf, sizeof (buf), stdin) return 0; <br/> printf ("\ n"); <br/> leftlen = (int) strlen (buf); <br/> while (leftlen> 0) <br/>{< br/> // send data to the server through the ssl channel <br/> outlen = SSL_write (ssl, buf + strlen (buf)-leftlen, leftlen ); <br/> if (outlen <0) return 0; // error <br/> if (outlen = 0) break; // sent <br/> leftlen-= outlen; <br/>}< br/> return 1; <br/>}</p> <p> int main (int argc, char * argv []) <br/>{< br/> BIO * bio_con; <br /> SSL_CTX * ctx; <br/> SSL * ssl; // ssl object <br/> long err; </p> <p> init_OpenSSL (); // initialize the OPENSSL library <br/> seed_prng (); // initialize the random data source </p> <p> ctx = setup_client_ctx (); // set the client context </p> <p> // create a connection BIO to the specified PORT on the SERVER <br/> bio_con = BIO_new_connect (SERVER ":" PORT ); <br/> if (! Bio_con) <br/>{< br/> int_error ("Creating a connection BIO error"); <br/>}< br/> if (BIO_do_connect (bio_con) <= 0) <br/>{< br/> int_error ("server connection error "); <br/>}</p> <p> // create an SSL object <br/> if (! (Ssl = SSL_new (ctx) <br/>{< br/> int_error ("An error occurred while creating an SSL object "); </p> <p >}< br/> // associate the SSL object with the connected BIO. <br/> SSL_set_bio (ssl, bio_con, bio_con ); </p> <p> // execute SSL handshake <br/> if (SSL_connect (ssl) <= 0) <br/>{< br/> int_error ("SSL handshake connection failed "); <br/>}</p> <p> // check after the SSL connection is executed <br/> // if the server certificate received is not "server" (when the certificate is generated ), an error is returned <br/> if (err = post_connection_check (ssl, "server "))! = X509_V_ OK) <br/>{< br/> fprintf (stderr, "-error: Connection certificate: % s \ n", X509_verify_cert_error_string (err )); <br/> int_error ("SSL object check error after connection"); <br/>}< br/> printf ("SSL connection enabled \ n "); <br/> if (do_client_task (ssl) <br/>{< br/> SSL_shutdown (ssl ); // close the SSL connection <br/>}< br/> else <br/>{< br/> SSL_clear (ssl ); // clear the SSL connection status <br/>}< br/> printf ("SSL connection closed \ n"); </p> <p> SSL_free (ssl ); // release the ssl object <br/> SSL_CTX_free (ctx); // release the ssl context object <br/> return 0; <br/>}< br/>

 

 

 

The server code implementation is as follows. For more information, see annotations.

# Include "commonlib. h "</p> <p> # define CAFILE DATA_DIR" \ rootcert. pem "<br/> # define cadir null <br/> # define SRVCERT DATA_DIR" \ server. pem "</p> <p> SSL_CTX * setup_server_ctx (void) <br/> {<br/> // generate a context object that supports SSL2.0 or SSL3.0 <br/> SSL_CTX * ctx = SSL_CTX_new (SSLv23_method ()); <br/> // load certificate path <br/> if (SSL_CTX_load_verify_locations (ctx, CAFILE, CADIR )! = 1) <br/> int_error ("An error occurred while loading the CA file"); <br/> // set the default certificate verification path <br/> if (SSL_CTX_set_default_verify_paths (ctx )! = 1) <br/> int_error ("An error occurred while loading the default CA file "); </p> <p> // load the server-side Private Key Certificate Chain <br/> if (SSL_CTX_use_certificate_chain_file (ctx, SRVCERT )! = 1) <br/> int_error ("An error occurred while loading the client certificate file"); <br/> // read the server private key, you need to provide a password for this private key. <br/> if (SSL_CTX_use_PrivateKey_file (ctx, SRVCERT, SSL_FILETYPE_PEM )! = 1) <br/> int_error ("An error occurred while loading the private key from the client certificate file"); </p> <p> // set it to require forced peer verification (client) certificate <br/> SSL_CTX_set_verify (ctx, SSL_VERIFY_PEER | callback, verify_callback); <br/> // set the maximum verification path length <br/> SSL_CTX_set_verify_depth (ctx, 4 ); <br/> return ctx; <br/>}</p> <p> int do_server_task (SSL * ssl) <br/>{< br/> int inlen, nread; <br/> char buf [80]; <br/> printf ("received from client: \ n"); <br/> for (nread = 0; nread <sizeof (buf ); Nread + = inlen) <br/>{< br/> // read data through BIO connection, read the data when the buffer zone is full or the other party closes and returns <br/> inlen = SSL_read (ssl, buf + nread, sizeof (buf)-nread); <br/> if (inlen <= 0) break; // error or no data on the client <br/> fwrite (buf + nread, 1, inlen, stdout ); // print the received information to the standard output <br/>}< br/> return (SSL_get_shutdown (ssl) & SSL_RECEIVED_SHUTDOWN )? 1:0; <br/>}</p> <p> void _ cdecl server_thread (void * arg) <br/>{< br/> long err; <br/> SSL * ssl = (SSL *) arg; <br/> // run the SSL handshake <br/> if (SSL_accept (ssl) <= 0) <br/>{< br/> int_error ("SSL handshake error"); <br/>}< br/> printf ("SSL connection enabled \ n "); <br/> // check after the SSL connection is executed <br/> // If the received client certificate is not "client" (this is what we wrote when generating the certificate ), an error is returned <br/> if (err = post_connection_check (ssl, "client "))! = X509_V_ OK) <br/>{< br/> fprintf (stderr, "-error: Connection certificate: % s \ n", <br/> X509_verify_cert_error_string (err )); <br/> int_error ("SSL object check error after connection"); <br/>}< br/> if (do_server_task (ssl )) // execute the server connection loop <br/>{< br/> SSL_shutdown (ssl ); // close the SSL connection <br/>}< br/> else <br/>{< br/> SSL_clear (ssl ); // clear the SSL connection <br/>}< br/> printf ("the SSL connection has been disabled \ n"); <br/> SSL_free (ssl ); // release the ssl object <br/> ERR_remove_state (0); // clear the error state <br/> _ e Ndthread (); // end thread <br/>}</p> <p> int main (int argc, char * argv []) <br/> {<br/> BIO * bio_acc, * bio_clnt; <br/> DWORD tid; // thread id <br/> SSL_CTX * ctx; <br/> SSL * ssl; </p> <p> init_OpenSSL (); // initialize the OPENSSL library <br/> seed_prng (); // initialize the random data source </p> <p> ctx = setup_server_ctx (); // initialize the Server Settings </p> <p> bio_acc = BIO_new_accept (PORT ); <br/> if (NULL = bio_acc) <br/>{< br/> int_error ("An error occurred while creating the server socket "); <br/>}< br/> if (BIO_do_a Ccept (bio_acc) <= 0) <br/>{< br/> int_error ("error when binding to server socket "); <br/>}< br/> for (;) <br/>{< br/> if (BIO_do_accept (bio_acc) <= 0) <br/>{< br/> int_error ("An error occurred while accepting the connection "); <br/>}< br/> // retrieve the current connection <br/> bio_clnt = BIO_pop (bio_acc); <br/> if (! (Ssl = SSL_new (ctx) <br/>{< br/> int_error ("An error occurred while creating an SSL object "); <br/>}< br/> // associate the SSL object with the connected BIO <br/> SSL_set_bio (ssl, bio_clnt, bio_clnt ); <br/> // create a sub-thread to process the connection and pass the ssl connection as a parameter to the sub-thread <br/> THREAD_CREATE (tid, server_thread, ssl ); <br/>}</p> <p> SSL_CTX_free (ctx); // release the ssl context object <br/> BIO_free (bio_acc ); // release the server package <br/> return 0; <br/>}

 

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.