Use OpenSSLAPI for security programming

Source: Internet
Author: User
Tags openssl api openssl library openssl version what is openssl
Article Title: Use OpenSSLAPI for security programming. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
The APIs used to learn how to use OpenSSL, the most famous Open Library for secure communication, are difficult because their documentation is incomplete. You can use the tips in this article to add this knowledge and use this API. After establishing a basic connection, you can view how to use the BIO library of OpenSSL to establish a secure connection and a non-secure connection. At the same time, you will learn some knowledge about error detection.
The OpenSSL API documentation is vague. There are not many tutorials on OpenSSL, so it may be difficult for beginners to use it in applications. So how can we use OpenSSL to implement a basic secure connection? This tutorial will help you solve this problem.
  
The difficulty of learning how to implement OpenSSL lies in its incomplete documentation. Incomplete API documentation usually prevents developers from using this API, which usually means it is doomed to fail. However, OpenSSL is still very active and is becoming more and more powerful. Why?
  
OpenSSL is the most famous Open Library for secure communication. In the result returned by searching "SSL library" in google, OpenSSL is at the top of the list. It was born in 1998 and originated from the SSLeay library developed by Eric Young and Tim Hudson. Other SSL toolkit includes gnu tls, which complies with the GNU General Public License release, and Mozilla Network Security Services (NSS) (refer to references later in this article for additional information ).
  
So what makes OpenSSL superior to gnu tls, Mozilla NSS, or all other libraries? License is a factor (see references ). In addition, gns tls (so far) only supports TLS v1.0 and SSL v3.0.
  
The release of Mozilla NSS follows both Mozilla Public License and gnu gpl, which allows developers to choose from. However, Mozilla NSS is larger than OpenSSL and requires other external libraries to compile the libraries. OpenSSL is completely self-contained. Similar to OpenSSL, most NSS APIs do not have documentation. Mozilla NSS received support for PKCS #11, which can be used for encryption tags such as smart cards. OpenSSL does not support this feature.
  
   Prerequisites
To fully understand and use this article, you should:
  
   Proficient in C Programming
Familiar with Internet communication and programming of Internet-Supported Applications.
You are not absolutely required to be familiar with SSL, because a brief description of SLL will be provided later. However, if you want a link to the article about SSL in detail, see references. It is good to have cryptographic knowledge, but this is not necessary.
  
   What is SSL?
SSL stands for the Secure Sockets Layer. It is a standard that supports secure communication over the Internet and integrates data cryptography into the Protocol. Data is encrypted before it leaves your computer and decrypted only after it reaches its intended destination. Certificates and cryptographic algorithms support all these operations. With OpenSSL, you will have the opportunity to understand them.
  
Theoretically, if the encrypted data is intercepted or eavesdropped before it reaches the target, the data cannot be cracked. However, since the computer changes faster than a year ago and the password translation method has developed, the possibility of cracking the encryption protocol used in SSL is also increasing.
  
SSL and secure connections can be used for any type of protocol on the Internet, whether HTTP, POP3, or FTP. You can also use SSL to protect Telnet sessions. Although SSL can be used to protect any connection, SSL is not required for each type of connection. If the connection transmits sensitive information, use SSL.
  
   What is 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. It also gives developers an understanding of OpenSSL capabilities. For more information about how to use the OpenSSL command line tool, see references.
  
   What do you need
The latest version of OpenSSL is required first. Refer to the references section to determine where to obtain the latest source code that can be compiled by yourself, or the latest binary file (if you do not want to spend time compiling ). However, for security reasons, we recommend that you download the latest source code and compile it yourself. Binary versions are usually compiled and released by third parties rather than OpenSSL developers.
  
Some Linux releases come with the binary version of OpenSSL, which is sufficient for learning how to use the OpenSSL library. However, if you want to do something practical, you must get the latest version and keep it updated.
  
We recommend that you obtain the RPM package from the release manufacturer to update your OpenSSL release version. For security reasons, we recommend that you use the latest release version. If your release version does not support the latest OpenSSL version, we recommend that you only overwrite the library file and do not overwrite the executable file. The FAQ document that comes with OpenSSL contains details about this.
  
Note that OpenSSL is not officially supported on all platforms. Although the manufacturer has tried its best to make it cross-platform compatible, there is still the possibility that OpenSSL cannot be used on your computer and/or operating system. See OpenSSL Web sites (links in references) for information on which platforms are supported.
  
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. I will not discuss this file, because it is not within the scope of this article. However, this template file has some very good comments, and if you search on the Internet, you can find a lot of tutorials about modifying this file.
  
   Header file and initialization
This tutorial uses only three header files: ssl. h, bio. h, and err. h. They are all located in the openssl subdirectory and are required to develop your project. To initialize the OpenSSL library, you only need three lines of code. Listing 1 lists all content. Other header files and/or initialization functions may be necessary for other functions.
  
Listing 1. Required header files
  
/* OpenSSL headers */
  
# Include "openssl/bio. h"
# Include "openssl/ssl. h"
# Include "openssl/err. h"
  
/* Initializing OpenSSL */
  
SSL_load_error_strings ();
ERR_load_BIO_strings ();
OpenSSL_add_all_algorithms ();
  
   Establish a non-secure connection
Whether the connection is secure or insecure, OpenSSL uses an abstract library named BIO to process various types of communication including files and sockets. You can also set OpenSSL as a filter, such as a filter for UU or Base64 encoding.
  
It is a little troublesome to fully describe the BIO database here, so I will introduce it at 1.1 points as needed. First, I will show you how to establish a standard socket connection. This operation requires fewer lines of code than the BSD socket library.
  
Before establishing a connection (whether secure or not), You must create a pointer to the BIO object. This is similar to creating a FILE pointer for a FILE stream in Standard C.
  
List 2. pointer
  
BIO * bio;
  
   Open connection
To create a new connection, you must call BIO_new_connect. You can specify both the host name and port number in the same call. You can also split it into two separate calls: one is the BIO_new_connect call that creates a connection and sets the host name, and the other is the BIO_set_conn_port (or BIO_set_conn_int_port) call that sets the port number.
  
In any case, once the BIO host name and port number are specified, the pointer will attempt to open the connection. Nothing can affect it. If a problem occurs during BIO object creation, the pointer will be NULL. To ensure the connection is successful, you must execute the BIO_do_connect call.
  
Listing 3. Create and open a connection
  
Bio = BIO_new_connect ("hostname: port ");
If (bio = NULL)
{
/* Handle the failure */
}
  
If (BIO_do_connect (bio) <= 0)
{
/* Handle failed connection */
}
  
Here, the first line of code uses the specified host name and port to create a new BIO object and format the object in the style shown. For example, if you want to connect to port 80 of www.ibm.com, the string will be www.ibm.com: 80. Call BIO_do_connect to check whether the connection is successful. If an error occurs, 0 or-1 is returned.
  
   Communicate with the server
Whether the BIO object is a socket or a file, the read and write operations on it are completed through the following two functions: BIO_read and BIO_write. Very simple, right? The wonderful thing is that it is always so.
  
BIO_read will try to read a certain number of bytes from the server. It returns the number of bytes read, 0, or-1. In the blocked connection, the function returns 0, indicating that the connection is closed, and-1 indicates that the connection has an error. In the case of non-blocking connections, 0 indicates no data is available, and-1 indicates a connection error. You can call BIO_should_retry to determine whether the error may be repeated.
  
Listing 4. Read from the connection
  
Int x = BIO_read (bio, buf, len );
If (x = 0)
{
/* Handle closed connection */
}
Else if (x <0)
{
If (! BIO_should_retry (bio ))
{
/* Handle failed read here */
}
  
/* Do something to handle the retry */
}
  
BIO_write will try to write bytes into the socket. It returns the number of bytes actually written, 0, or-1. The same as BIO_read, 0, or-1 does not necessarily indicate an error. BIO_should_retry is the way to identify the problem. If you need to retry the write operation, it must use the same parameters as the previous one.
  
Listing 5. Write to connection
  
If (BIO_write (bio, buf, len) <= 0)
{
If (! BIO_should_retry (bio ))
Related Article

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.