Extended knowledge of mcrypt encryption for PHP


Today we’re going to learn about an outdated extension mcrypt in PHP. Before php7, this extension was built-in and released with the PHP installation package, but now it is not available in the new version of PHP. If we need to use this extension, we need to install it separately, and an outdated warning will be reported when using it. Therefore, when we learn to use these functions, we need to use @ to suppress error messages. Of course, the reason why this set of extensions is warned of obsolescence is that PHP more recommends using OpenSSL to handle similar encryption capabilities.

Modules and algorithms

Mcrypt mainly uses the mcrypt tool for encryption, so in CentOS or other operating systems, we need to install libmcrypt devel to use this extension. If you can’t install it in yum, you can update the yum source directly.

Mcrypt contains many modules and algorithms. The algorithm needs no explanation. It is the way to encrypt data. The modules, including CBC, OFB, CFB and ECB, are a series of grouping and streaming encryption modes, including recommended modules and secure modules. For specific differences, you can consult relevant materials. Here we take a look at the modules and algorithms supported in our environment.

$algorithms = @mcrypt_list_algorithms();
// Array
// (
//     [0] => cast-128
//     [1] => gost
//     [2] => rijndael-128
//     [3] => twofish
//     [4] => arcfour
//     [5] => cast-256
//     [6] => loki97
//     [7] => rijndael-192
//     [8] => saferplus
//     [9] => wake
//     [10] => blowfish-compat
//     [11] => des
//     [12] => rijndael-256
//     [13] => serpent
//     [14] => xtea
//     [15] => blowfish
//     [16] => enigma
//     [17] => rc2
//     [18] => tripledes
// )

$modes = @mcrypt_list_modes();
// Array
// (
//     [0] => cbc
//     [1] => cfb
//     [2] => ctr
//     [3] => ecb
//     [4] => ncfb
//     [5] => nofb
//     [6] => ofb
//     [7] => stream
// )

mcrypt_ list_ The algorithms() function can obtain all supported mcrypt algorithms in the current environment. And mcrypt_ list_ Modes () prints out all supported modules in the current environment. Note that these contents are different in some versions of PHP or some systems. When using mcrypt related encryption capabilities, these two items are used together. Therefore, it is necessary to determine the modules and algorithms supported in the current environment in advance in the environment where mcrypt needs to run.

Encrypt and decrypt data

$key = hash('sha256', 'secret key', true);
$input = json_encode(['id'=>1, 'data'=>'Test mcrypt!']);

$td = @mcrypt_module_open('rijndael-128', '', 'cbc', '');
$iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_URANDOM);
@mcrypt_generic_init($td, $key, $iv);
$encrypted_data = @mcrypt_generic($td, $input);

echo $encrypted_data, PHP_EOL;
// ��I      $�3���gE�ǣu(�9n�����
//                            p�>P

$td = @mcrypt_module_open('rijndael-128', '', 'cbc', '');

@mcrypt_generic_init($td, $key, $iv);
$data = @mdecrypt_generic($td, $encrypted_data);
echo $data, PHP_EOL;
// {"id":1,"data":"Test mcrypt!"}


There are a lot of codes and they are messy. Let’s look at them one by one.

First, we determine an encrypted key, and then input is the data we want to encrypt. For example, we need to encrypt a JSON data. In fact, the key can be a string, but we also hash the key here. We explained the contents related to the hash in detail in the last article.

The next step is to use mcrypt_ module_ Open () opens an encryption module handle. Here we use rijndael-128 algorithm and CBC module. Then use mcrypt_ create_ IV () creates an IV, which is an initialization vector. The value of the initialization vector varies according to the cryptographic algorithm. The most basic requirement is “uniqueness”, that is, the same key does not reuse the same initialization vector. This feature is very important in both packet encryption and stream encryption. I believe that if you have done WeChat or Alipay related interface communication, you will see this IV attribute when decrypting validation data.

Using mcrypt_ Generic() generates encryption results, using mcrypt_ generic_ Deinit() ends the generation initialization, and finally passes mcrypt_ module_ Close() closes the encryption module handle. In this way, a set of mcrypt encryption process is completed.

Similarly, the decryption process is similar to the encryption process, except that we use mdecrypt_ General () function to decrypt.

Another way to encrypt and decrypt data

The above encryption process is very troublesome and complex. In fact, mcrypt also provides a simpler encryption function.

$string = 'Test MCrypt2';
$algorithm = 'rijndael-128';
$key = md5( "mypassword", true);
$iv_length = @mcrypt_get_iv_size( $algorithm, MCRYPT_MODE_CBC );
$iv = @mcrypt_create_iv( $iv_length, MCRYPT_RAND );

$encrypted = @mcrypt_encrypt( $algorithm, $key, $string, MCRYPT_MODE_CBC, $iv );
$result = @mcrypt_decrypt( $algorithm, $key, $encrypted, MCRYPT_MODE_CBC, $iv );

echo $encrypted, PHP_EOL; // \

We still have to prepare the data, algorithm, key and IV vector to be encrypted. Then use mcrypt directly_ Encrypt() and mcrypt_ Decrypt() to encrypt / decrypt. Is it much more convenient.


Compared with hash, mcrypt is a decryptable symmetric encryption form. As for what is symmetric and asymmetric encryption, we will explain it in detail in the study of OpenSSL extension, while hash encryption is a one-way encryption form, which can not obtain the original data through the reverse calculation of the encrypted data. They all have different application scenarios, but as prompted by PHP, mcrypt is already an extension that is not recommended. Therefore, we just conduct a simple encryption / decryption test here. If you are useful, you can learn more deeply according to the manual.

Test code:


Reference documents:



Official account: hard core project manager

Add wechat / QQ friends: [xiaoyuezigonggong / 149844827] get free PHP and project management learning materials

Tiktok, official account, voice, headline search, hard core project manager.

Station B ID: 482780532

Recommended Today

Hive built-in function summary

1. Related help operation functions View built-in functions: Show functions; Display function details: desc function ABS; Display function extension information: desc function extended concat; 2. Learn the ultimate mental method of built-in function Step 1: carefully read all the functions of the show functions command to establish an overall understanding and impression Step 2: use […]