During your career, you will have to encrypt sensitive user data that should be decrypted sometimes in a future. Encyption can be helpful if sensitive data is exchanged between two different applications. If this your case, the MCrypt library provides a good solution.

In new versions of PHP, MCrypt library comes with it, that means you don’t have to configure PHP. In our example, I will show to you how to encrypt sensitive user data like bank number and fallowing this pattern, you can encrypt any other data.

In the following few sections I’m trying to explain and teach several security concepts to which people dedicated entire careers. This is just tip of security iceberg, but it is better to know something then nothing.

Encryption

When we are talking about encryption, then the first station is encryption algorithm also called cipher. MCrypt library comes with several different algorithms, and every algorithm encrypts the data in different way. Very important thing here is the fact that all algorithms are known and publicly available and they are not hidden. The only thing that is hidden is key which is under your control.

Let us first list all MCrypt ciphers by executing mcrypt_list_algorithms function.

It would take days and days to provide detailed explanation of every algorithm, and in my post I will concentrate only on one algorithm called Rijndeal or AES (Advanced Encryption Standard). There are dozens of web sources where you can read how every algorithm works (remember, their implementation is publicly available). This algorithm is very popular and secure and it has been adopted by U.S. government. The cipher comes with three different key lengths: 128, 192 and 256 bits. In my tutorial I will use 256 (32 bytes) bits key length.

To start with MCrypt library we have to invoke mcrypt_module_open(algorithm, cipher, mode, mode_dir) function. We decided which cipher to use, now we just have to define which mode to use. In order to list all modes, execute function mcrypt_list_modes(). The following modes are available:

There are four main modes: ECB (electronic codebook), CBC (cipher block chaining), CFB (cipher feedback) and OFB (output feedback). In my tutorial, I will use CBC which suit most of our needs, especially when encrypting blocks of text.

Now we can call mcrypt_module_open function.

The second step is to generate initialization vector (IV). This may be required, optional or unnecessary, depending on the mode being used. In our case, CBC mode requires IV.

Function mcrypt_enc_get_iv_size returns proper size of IV for the cipher being used.

The final step, prior data encryption is to create a buffers that MCrypt needs to perform encryption:

As you can see, the second parameter is variable called $key. This is your private key that is used during encryption process, and only person knowing this key will be able to decrypt the data.

This key should be 32 bytes long if you are using rijndael-256 cipher, 24 bytes long if you are using rijndael-194 and 16 bytes long if you are using rijndael-128. Obviously, any 32 characters long string is a valid key, although, I will show you better way for generating keys.

Here is complete example how to encrypt the data.

Variable $key is generated as output of md5() function which generates 32 characters long hash from original string.

After data encryption process, we close the buffers and opened MCrypt module.

If you need to store $encryptedData to the database or to send it to other application, then use base64_encode() function. See examples below.

In my case, value of the variable $encryptedData is equal to:

%y��u�|�~�i[/h9�_e��� \��Sz�

Please note that if you execute code above, variable $encryptedData might hold different value. That is because initialization vectors are not the same in your and my case.

Decryption

During decryption process the steps are almost the same. Instead of using mcrypt_generic() function, you should use mdecrypt_generic() function. Here is an example:

During decryption process, $iv and $key variables should be exact the same as during encryption process. If this is not the case, then decryption will fail and you will get bad results.

Here is a full example that demonstrates encryption and decryption:

How to save data to the database

Sometimes you will want to save encrypted data to the database, or to send it to another web application using web services. The best way to do it is to use base64_encode() before you save data to the database (or send the data to another web application), and base64_decode() before decryption process starts. Here is full example (some of the code is intentionally omitted so you can see the usage of base64_encode() and base64_decode() functions):

How to generate key more safely

In my previous examples, I generated private key as output from MD5 hash function. Let’s say there is an accidental echo statement in production environment, which prints the value of the $key variable, meaning everyone can see it. This is obviously a problem. Let us go step further and let us try to generate a private key in a way that even if it is printed using echo statement, it is not valid.

As we said, the key is composed of 32 characters. Every ASCII character is defined as 1 byte, but not all ASCII characters are visible when they are printed.

ASCII Table

ASCII Table

As you can see, ASCII characters in most left table are called “ASCII control characters” and they are not visible/printable, but they are still valid characters. If control characters are part of our key, then even if our key is printed, those characters are not visible and key will still be “safe”.

For this purpose, instead of MD5 function that will return you “printable” string, use openssl_random_pseudo_bytes(int $numberOfBytes) function (from PHP 7 you can use function random_bytes ).

For any questions, please leave comments or contact me: code.epicenter (at) gmail.com.

How to use MCrypt Library in PHPhttp://code-epicenter.com/wp-content/uploads/2016/04/MCrypt-Library-PHP.jpghttp://code-epicenter.com/wp-content/uploads/2016/04/MCrypt-Library-PHP-150x150.jpgAmir DuranLibrariesPHPProgrammingTutorialscipher,decryption,encryption,MCrypt,PHP
During your career, you will have to encrypt sensitive user data that should be decrypted sometimes in a future. Encyption can be helpful if sensitive data is exchanged between two different applications. If this your case, the MCrypt library provides a good solution. In new versions of PHP, MCrypt library comes with it,...