Use the OpenSSL API to establish secure connections-two-way authentication

Source: Internet
Author: User
Tags openssl openssl api openssl library rfc ssl connection what is openssl asymmetric encryption
Secure programming with the OpenSSL API
First, Concept: 1. What is SSL.   SSL is an abbreviation, the full name is Secure Sockets Layer.   It is the standard that supports secure communication over the Internet and integrates data cryptography into the protocol.   The data is encrypted before it leaves your computer and is decrypted only if it reaches its intended target. The certificate and Cryptography algorithms support all of this, and with OpenSSL you will have the opportunity to experience them firsthand.
You can use SSL and secure connections for any type of protocol on the Internet, whether HTTP, POP3, or FTP.   You can also use SSL to protect Telnet sessions.   Although you can secure any connection with SSL, you do not have to use SSL for each type of connection.    If the connection transmits sensitive information, you should use SSL.   2. What is OpenSSL.   OpenSSL is more than just SSL.   It can implement message digest, file encryption and decryption, digital certificates, digital signatures, and random numbers. The content of the OpenSSL library is very much, far from an article can accommodate.
OpenSSL is not just an API, it is also a command-line tool.   Command-line tools can do the same thing as the API, and further, you can test SSL servers and clients.      It also gives developers a sense of OpenSSL's capabilities.   The first thing you need is the latest version of OpenSSL. However, for security reasons, I recommend that you download the latest source code and compile it yourself.
A binary version is usually compiled and distributed by a third party rather than by a OpenSSL developer.   Some Linux distributions come with a binary version of OpenSSL, which is sufficient to learn how to use the OpenSSL library, and if you want to use OpenSSL to generate certificate requests and digital certificates, you must create a configuration file.   In the Apps folder of the OpenSSL package, there is an available template file named Openssl.cnf. However, the template file has some very good comments, and if you search the Internet, you can find many tutorials to discuss modifying the file.
3. What is a digital certificate. The simplest form of a    digital certificate is an asymmetric encryption key (asymmetric cryptography key).    Currently there are some identifying information in the standards for digital certificates, which are included in the key.    A typical digital certificate contains:    Owner's name (if the certificate is used on a WEB server, then the name is the complete domain) and contact information,    also has a valid date range,    and a security signature to verify that the certificate has not been tampered with.       Digital certificates can be simply created using the OpenSSL command-line tool or other tools for this purpose.    But any digital certificate created by anyone has a problem with trust.    digital certificate is more than just an encryption key, it is an online voucher. The    certificate will prove your identity to those who are trying to communicate with you.    to show trust relationships, digital certificates can be signed by a certification authority (ca-certificate Authority) authority.       Certification Authority acts as a trusted third party in the field of digital security.    as it is difficult to prove an entity's identity in an online domain, certification authority takes over the challenge.    they provide proof of identity for those who purchase or sign the certificate.    therefore, to trust a certificate, the user only needs to trust the certificate authority.    users demonstrate their trust in the certification authority by owning and using the CA's trust certificate.   verisign and Thawte are very well known for their certification authority.       If the security of a certificate has been compromised, the certificate is discarded-that is, it is declared invalid.    when a certificate is declared invalid, it is not possible for the CA to notify everyone who owns the copy of the certificate.    Conversely, a CA publishes a certificate revocation list (crl-certificate revocation list).    browsers and other programs that use digital certificates can verify that this certificate has beenhas been revoked by its owner or CA. The revocation of       certificates can also be checked using the OCSP protocol.   OCSP represents the online certificate status Protocol (On-line Certificate Status agreement)    it is defined in RFC 2560.   openssl features both OCSP and CRL functionality, but the introduction of these features is beyond the scope of this article.    the current standard for digital certificates is X.509, which is defined in RFC 3280.      openssl has a library dedicated to digital certificates.    The source code for this library is located in the crypto/x509 and Crypto/x509v3 directories.    source code defines several OpenSSL structures related to X.509 certificates for the processing of digital certificates:    structure               function   x509           Contains all data about a digital certificate.   x509_algor       provides an algorithm for this certificate design.   x509_val         the time span in which the certificate is valid.   x509_pubkey      Certificate's public key algorithm, usually RSA or DSA.   x509_sig       Certificate Hash signature.   x509_name_entry the entries for the data that the certificate contains.   x509_name       The stack that contains the name items.    These are just a few of the structures involved.    most of the X.509 structures used in OpenSSL are almost never used in your application.    on top of these structures, there are functions to handle digital certificates.    These functions are named for the structure they apply to.    For example: a function that begins with the name X509_name, usually applied to a x509_name structure.
4. What is the handshake before doing business.   A secure connection requires a handshake after the connection is established.   During the handshake, the server sends a certificate to the client and then the client verifies the certificate against a set of trusted certificates.   It will also check the certificate to make sure it does not expire. To verify that the certificate is trustworthy, you need to load a trusted certificate library ahead of the connection establishment.
   the client sends a certificate to the server only if a request is made by the server.    This process is called Client authentication.    use certificates to pass password parameters between the client and the server to establish a secure connection.    Although the handshake is made after the connection is established, the client or server can request a new handshake at any time.       handshake:    safe and credible handshake means that both sides of the business believe that what they are doing is good for both parties.    unsafe handshake marks only one side will have a correct understanding of the transaction.   1. Starting a handshake on a connection usually begins with the client saying "Hello" to the server. The     helllo message (which is what the specification says) contains: The version number of the      client SSL protocol,      The types of cryptographic algorithms, the number of random numbers generated by     , the various information required for communication between      and other servers and clients.   2. The server will respond with its own Hello message, which includes the version number of the     SSL protocol, the type of the      encryption algorithm,      random numbers,      and other related information,      at the same time the server will also send its own certificate to the client.      Note: If the client also authenticates the connection, the server sends a request requesting the client's certificate.   3. After the client receives the hello message from the server, the digital certificate is validated. The legality check of      service certificate includes:      certificate expiration,      issuing server certificate ca  is reliable,      the public key of the publisher's certificate correctly unlocks the digital signature of the publisher for the server certificate,      the domain name on the server's certificate matches the actual domain name of the servers.      if the legality verification fails, the communication will be disconnected;      if the legality validation is passed, the  4 step will continue.   4. The client randomly generates a "symmetric key" for subsequent communications,      encrypts it with the server's public key (the server's public key is obtained from the server's certificate in step 2),       then passes the encrypted "pre-master password" to the server.   5. If the server requires the client's authentication (optional during the handshake),      user can create a random number and then use their own private key for data signature (hash value),       will include this random number with signature,      client's own certificate      and the encrypted "pre-master password"       pass to the server together.   6. If the server requires the customer's identity authentication, the server must verify the legality of the client certificate and the signed random number, and the legality check of the      client certificate includes:       The validity of the customer's certificate usage date,      the reliability of the CA providing the certificate to the customer,      the public key of the issuing CA correctly unlocking the digital signature of the issuing CA for the client certificate ,      check that the customer's certificate is in the certificate revocation list (CRL).      If the inspection fails, the communication is immediately interrupted;      if the test passes, the server will unlock the encrypted "Pre-master password" with its own private key,       then use the Pre-master password to create the master communication password via an algorithm.      Note: The client will also generate the same master communication password via the same algorithm.   7. The server and the client use the same master password, the "Call password",      a symmetric key for secure data communication for SSL protocol encryption and decryption communication.      in the process of SSL communication also completes the integrity of data communication, to prevent any changes in data communication.   8. The client sends a message to the server indicating that the primary password in step 7 used in the subsequent data communication will be a symmetric key,      also notifies the server client that the handshake process is over.   9. The server sends a message to the client indicating that the primary password in step 7 used in the subsequent data communication is a symmetric key,      also notifies the client that the end of the handshake process is over. The  10.ssl handshake part ends, the SSL secure channel data communication begins,      the client and the server begin to use the same symmetric key to carry on the data communication, simultaneously carries on the verification of the communication integrity.      Client said: Hello

Service side said: Hello

Ii. development: 1. Header files: This tutorial uses only three headers: (They are all in the INCLUDE/OPENSSL subdirectory) Ssl.h SSL's primary data structure is defined in ssl.h.      Bio.h regardless of whether the connection is secure or unsafe, OpenSSL uses an abstract library called BIO to handle various types of communication, including files and sockets. Err.h
2. Initialization:    to initialize the OpenSSL library, you need only three lines of code:   //initialize the SSL algorithm library function, you must call this function before calling the SSL series function.   ssl_library_init ();   //load SSL error message   ssl_load_error_strings ();   //load the error message for the BIO Abstract Library   err_load_bio_strings ();   //loads all cryptographic and hash functions   openssl_add_all_algorithms ();    3.1. Establish a non-secure connection:   //First, I'll show you how to build a standard socket connection.   //compared to using the BSD socket library, the operation requires fewer lines of code.   //to create a pointer to a BIO object before establishing a connection, whether secure or not.   //this is similar to creating a file  pointer for a file stream in standard C.   bio* BIO = NULL;      //Creating a new connection requires calling Bio_new_connect.   //You can specify both the host name and the port number in the same call.   //can also be split into two separate calls:   //is a bio_new_connect call to create a connection and set the hostname,   //one to set the port number bio_set_ Conn_port (or Bio_set_conn_int_port) call.   //once the hostname and port number of the BIO have been specified, the pointer attempts to open the connection.   //If you encounter problems creating a BIO object, the pointer will be NULL.   //the following line of code creates a new  bio object using the specified hostname and port. The   //parameter string can be WWW.IBM.Com:80    bio = Bio_new_connect ("Hostname:port");   if (NULL = = bio)   {      //processing failure   }    &nbsp ;  //you must perform a bio_do_connect call to ensure a successful connection.   //returns 0 OR-1 if an error occurs.   if (0 >= bio_do_connect (BIO))   {      //processing connection Failure    }
3.2.1. Setting for secure connections:   //A few more lines of code for a secure connection.   //also requires a pointer with another type of ssl_ctx. This structure holds some SSL information.   //You can also use it to establish an SSL connection through the BIO library.   //can create this structure by calling Ssl_ctx_new using the SSL method function,   //the parameter of the method function is usually Tlsv1_client_method () (formerly sslv23_ Client_method).   ssl_ctx* CTX = ssl_ctx_new (Tlsv1_client_method ());      //also requires a pointer to another SSL type to maintain the SSL connection structure (which is necessary for some connections that can be completed in a short time).   //can also use this SSL pointer to check connection information or set additional SSL parameters later.   ssl* SSL = NULL;    3.2.2. Load Trusted certificates:   //After the context structure is created, a trusted certificate library must be loaded. This is required to successfully validate each certificate.   //If you cannot confirm that the certificate is trustworthy, OpenSSL marks the certificate as invalid (but the connection can continue).   //OpenSSL comes with a set of trustworthy certificates. They are located in the Certs/demo directory of the source file directory tree.   //However, each certificate is a separate file, which means that each certificate needs to be loaded separately.   //in the Certs directory, there is also a subdirectory of the expired that holds expired certificates, and an error occurs when attempting to load the certificates.   //before a digital certificate is trusted for authentication,   //must provide a default trust certificate for the OpenSSL Ssl_ctx object created when the secure connection is set up,   // This can be provided in several ways,   //but the easiest way is to save this certificate as a PEM file,   // It is loaded into   //using the     //ssl_ctx_load_verify_locations (CTX, file, path);  OpenSSL.   //the function has three parameters:   //ctx  -context pointer (ssl_ctx_new function return);

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.