Reader small image

You're reading from  Demystifying Cryptography with OpenSSL 3.0

Product typeBook
Published inOct 2022
PublisherPackt
ISBN-139781800560345
Edition1st Edition
Concepts
Right arrow
Author (1)
Alexei Khlebnikov
Alexei Khlebnikov
author image
Alexei Khlebnikov

Alexei Khlebnikov has more than 20 years of professional experience in IT, where he worked in different roles - software developer, system administrator, DevOps engineer, technical leader, architect and project manager. During those years Alexei worked with many technologies - Security, Artificial Intelligence, Web Development, Embedded, Mobile, and Robotics. Among other companies, Alexei worked in Opera Software on the famous Opera Internet browser. Alexei has always been interested in security. He was one of the maintainers of security-related Opera browser modules, responsible for cryptography, SSL/TLS and integration with OpenSSL. He was also a member of the Security Architects group, responsible for the security of the Opera browser. Now Alexei lives in Oslo, Norway, and works as a senior consultant for Bespoke AS. He is also the leader of the Architects group at his current employer.
Read more about Alexei Khlebnikov

Right arrow

Symmetric Encryption and Decryption

In this chapter, we will learn about the important concepts of symmetric encryption – cipher, encryption mode, and padding. There will be an overview of modern ciphers, encryption modes, and padding types and recommendations on which technology to use in which situation. The usage of those technologies will be illustrated by code examples. This is the first chapter that will contain code examples; thus, we will also need to learn how to initialize older versions of the OpenSSL library if we ever want to run our code with an older version of OpenSSL.

We are going to cover the following topics in this chapter:

  • Understanding symmetric encryption
  • An overview of the symmetric ciphers supported by OpenSSL
  • Block cipher modes of operation
  • Padding for block ciphers
  • How to generate symmetric encryption keys
  • Downloading and installing OpenSSL
  • How to encrypt and decrypt with AES on the command line
  • Initializing and...

Technical requirements

This chapter will contain commands that you can run on a command line and C source code that you can build and run. For the command-line commands, you will need the openssl command-line tool with OpenSSL dynamic libraries. For building the C code, you will need OpenSSL dynamic or static libraries, library headers, a C compiler and, a linker. If you don’t have OpenSSL components installed, this chapter will teach you how to install them.

We will implement some example programs in this chapter in order to practice what we are learning. The full source code of those programs can be found here: https://github.com/PacktPublishing/Demystifying-Cryptography-with-OpenSSL-3/tree/main/Chapter02.

Understanding symmetric encryption

Symmetric encryption is used for encrypting data with an encryption key. Note that an encryption key is not the same as a password, but an encryption key can be derived from a password. How to do so will be explained in a Chapter 5, Derivation of an Encryption Key from a Password.

Symmetric encryption is called symmetric because the same key is used both for encryption and decryption operations. There is also asymmetric encryption, where different keys (public and private) are used for encryption and decryption. Asymmetric encryption will be covered in Chapter 6, Asymmetric Encryption and Decryption.

In order to symmetrically encrypt something, you have to use a symmetric encryption algorithm. This kind of algorithm is also called a cipher. It is worth noting the term cipher has a broad meaning and can refer to any encryption or encryption-related algorithm, including algorithms for symmetric and asymmetric encryption, message digests, and even...

An overview of the symmetric ciphers supported by OpenSSL

In this section, we will review the symmetric encryption algorithms supported by OpenSSL, but, first, we need to introduce some concepts that will help us to understand the differences between ciphers, their properties, and their advantages and disadvantages. Symmetric ciphers are divided into two categories: block ciphers and stream ciphers.

Comparing block ciphers and stream ciphers

Block ciphers operate on blocks of data. For example, a popular Advanced Encryption Standard (AES) cipher has a block size of 128 bits, meaning that the cipher encrypts or decrypts data in 128-bit blocks. If the amount of data is larger than the block size, the data is split into blocks of the needed size needed for processing. If the plaintext length is not multiple of the block size, the last block is usually padded up to the block size according to the chosen padding type. Thus, in most block cipher operation modes, the ciphertext length...

Block cipher modes of operation

Block ciphers can operate in different encryption modes, also known as modes of operation. As we already know, block ciphers encrypt plaintext data block by block. Encryption modes specify how blocks of ciphertext are chained together. We are now going to review most popular operation modes.

Reviewing the Electronic Code Book mode

The simplest operation mode is Electronic Code Book (ECB). In this mode, each plaintext block is encrypted into a ciphertext block using only the encryption key, without using an IV or previous plaintext or ciphertext blocks. Then, the ciphertext blocks produced are concatenated.

The ECB mode can be illustrated by the following image:

Figure 2.3 – How ECB mode works

Image Source: Wikipedia, licensing: Public Domain

In the ECB mode, the same plaintext always produces the same ciphertext. It is a security issue because patterns in the plaintext are preserved in the ciphertext and are...

Padding for block ciphers

In CBC mode, block ciphers encrypt plaintext data block by block – but what happens to the last plaintext block, which in most cases, is smaller than the block size? It cannot be encrypted as is, because a block cipher requires a complete data block as input. Thus, the last plaintext block is padded up to the block size.

OpenSSL can add padding automatically when finalizing encryption and remove it when finalizing decryption. This feature can be disabled – in such a case, the developer must pad and unpad the plaintext data himself.

Cryptographers invented different types of padding. For symmetric encryption, OpenSSL only supports Public Key Cryptography Standard number 7 padding (PKCS #7 padding), also known as PKCS7 padding, simply PKCS padding, or standard block padding. PKCS #7 padding consists of N bytes, each having the value N. For example, if the cipher block size is 16 bytes (128 bits) and the last block of plaintext is only 10...

How to generate a symmetric encryption key

Generating an encryption key for symmetric encryption is surprisingly easy. You just request the needed amount of random bytes from your cryptographically secure random generator!

Which random generator is considered cryptographically secure? It is a random generator that generates bytes that are extremely hard to predict. The unpredictability of generated random bytes is accomplished by using the entropy caused by unpredictable events from the outside world. Often, cryptographically secure random generators use the entropy caused by the unpredictable timing of the input from a keyboard and mouse. If the keyboard and mouse are unavailable, for example, when an application is running in a container, then another source of entropy can be used, such as microfluctuations in the CPU speed. Another common entropy source is a ring oscillator that can be included in the CPU or another chip.

What is the correct amount of random bytes? It is the...

Downloading and installing OpenSSL

We have now learned enough about the building blocks of symmetric encryption. It is time to use our knowledge to encrypt some data using OpenSSL, but first, we need to get the required components of OpenSSL.

The OpenSSL toolkit is distributed from its official website (https://www.openssl.org/) in the form of source code. If you are a software developer, you can compile OpenSSL using the documentation supplied with the source code. Compiling OpenSSL from the source is the preferred way if you want a particular version of OpenSSL or want to compile it with specific options.

You can also get OpenSSL in a compiled form. Almost all Linux distributions contain OpenSSL in the form of one or several installable packages. For example, in order to install OpenSSL on Debian or Ubuntu Linux, you only need to issue one command:

$ sudo apt install openssl libssl3 libssl-dev libssl-doc

Another Linux distribution may use a different command, but for...

How to encrypt and decrypt with AES on the command line

We are going to encrypt a file using the openssl command-line tool.

Let’s generate a sample file:

$ seq 1000 >somefile.txt

Using our knowledge of the symmetric encryption concepts, we are choosing the following parameters for our encryption:

  • Cipher: AES-256
  • Operation mode: CBC (we should have chosen GCM, but that mode is not supported by the command-line tool)
  • Padding type: standard block padding

How can we find out how to encrypt the command line from the documentation? We can begin with the openssl tool man page:

$ man openssl

On that man page, we can see different subcommands that the openssl tool supports. From the man page, we can figure out that we need the enc subcommand. We can then refer to the openssl-enc man page for documentation on the enc subcommand:

$ man openssl-enc

From the openssl-enc man page, we can figure out which parameters the subcommand needs. We see...

Initializing and uninitializing OpenSSL library

As of version 1.1.0, the OpenSSL library does not require explicit initialization and uninitialization. The library will automatically initialize and uninitialize.

However, it is still possible to initialize OpenSSL explicitly if some non-standard initialization is needed. It is also possible to uninitialize explicitly, but it is discouraged, especially in multithreaded programs or if OpenSSL may be used by both the program and another library in the same process. Note that after uninitialization, it is not possible to initialize OpenSSL again.

Explicit initialization is done by calling the OPENSSL_init_ssl() function. Explicit uninitialization is done by calling the OPENSSL_cleanup() function.

Older versions of OpenSSL, below 1.1.0, will not initialize automatically. If you need to use an old OpenSSL version, you have to initialize it explicitly, using now-deprecated functions called SSL_library_init() and EVP_cleanup().

...

How to encrypt with AES programmatically

When using OpenSSL as a library, we do not have to limit ourselves to the functionality that the openssl tool provides. openssl is a good tool, but it does not expose the whole functionality of OpenSSL. For instance, openssl enc does not support encryption or decryption in GCM, but OpenSSL as a library allows us to do that.

In this section, we are going to develop a program that can encrypt a file using an AES-256 cipher in GCM. We will call our program encrypt.

In order to avoid passing too many values on the command line, we will store the IV and authentication tag in the encrypted file. Unlike the encryption key, the IV and auth tag are public information and do not have to be kept secret. The format of the encrypted file will be the following:

Table 2.1 – The encrypted file format

Our encryption program will need three command-line arguments:

  1. Input file name
  2. Output file name
  3. Encryption...

How to decrypt with AES programmatically

In this section, we are going to develop the decrypt program that can encrypt a file encrypted by the encrypt program.

Our decryption program will be similar to the encryption program and will also take three command-line arguments:

  1. Input file name
  2. Output file name
  3. Encryption key, hex-encoded

This time, the input file is the encrypted file created by the preceding encrypt program.

Let’s make a high-level plan, similar to how we did before:

  1. Read the IV from the input file.
  2. Initialize decryption.
  3. Decrypt chunk by chunk, reading plaintext chunks from the input file and writing the resulting plaintext chunks into the output file.
  4. Read the authentication tag from the input file and set it into the cipher context.
  5. Finalize decryption.

As we can see, the decryption plan is very similar to the encryption plan – initalize, process, and finalize. Let’s see how it is implemented...

Summary

In this chapter, we have learned what symmetric encryption is and how it differs from asymmetric encryption. We also learned what a cipher is, what block ciphers and stream ciphers are, how cipher security is measured, and how much security is enough. Then, we learned which ciphers are supported by OpenSSL, which you should use in which situation, and which ciphers you should avoid. We also learned which cipher operation modes exist, how they differ, and which you should use.

We discussed padding, why it exists, and in which cases you should use it. We also covered oracle and how to download and install OpenSSL. We explored and saw what is included in the OpenSSL toolkit, how to initialize the OpenSSL library, and how to compile and link your program with the OpenSSL library. Finally, we learned how to generate an encryption key and an IV, how to encrypt and decrypt a file using the OpenSSL command-line tool, and how to encrypt and decrypt a file programmatically using the...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Demystifying Cryptography with OpenSSL 3.0
Published in: Oct 2022Publisher: PacktISBN-13: 9781800560345
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Alexei Khlebnikov

Alexei Khlebnikov has more than 20 years of professional experience in IT, where he worked in different roles - software developer, system administrator, DevOps engineer, technical leader, architect and project manager. During those years Alexei worked with many technologies - Security, Artificial Intelligence, Web Development, Embedded, Mobile, and Robotics. Among other companies, Alexei worked in Opera Software on the famous Opera Internet browser. Alexei has always been interested in security. He was one of the maintainers of security-related Opera browser modules, responsible for cryptography, SSL/TLS and integration with OpenSSL. He was also a member of the Security Architects group, responsible for the security of the Opera browser. Now Alexei lives in Oslo, Norway, and works as a senior consultant for Bespoke AS. He is also the leader of the Architects group at his current employer.
Read more about Alexei Khlebnikov