Home >Backend Development >PHP Tutorial >Introduction to using openssl to replace mcrypt in PHP7.1
This article mainly introduces the detailed examples of using openssl to replace mcrypt in PHP7.1. This article introduces you in very detail. Friends who need it can refer to it
In PHP development, use mcrypt related functions AES encryption and decryption operations can be easily performed, but the mcrypt extension is abandoned in PHP7.1, so another implementation must be found. Replacing mcrypt with openssl is already pointed out in the migration manual, but no specific example is given. There are many examples online that can replace most scenarios, but the details are not explained. Similarly, simply using online examples may lead to compatibility issues before and after code replacement in certain code scenarios. Let’s talk about the specific codes and reasons below.
First we give the replacement code directly, and then analyze the problem from the code. (The algorithm analyzed in this article is AES-128-CBC)
Replacement example
The example will show two ways of using mcrypt, mainly The difference lies in the padding (padding will be explained below). During the entire encryption and decryption process, a more complete code will automatically implement filling and removal of filling, and a simpler code will directly ignore the filling, but both methods can run normally; in actual development (versions before 7.1), It is recommended to add padding. Please see the following specific example:
mcrypt does not use padding
mcrypt encryption:
$key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; $iv = 'aaaaaaaaaaaaaaaa'; $data = 'dataString'; $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); mcrypt_generic_init($cipher, $key, $iv); $cipherText256 = mcrypt_generic($cipher, $data); mcrypt_generic_deinit($cipher); return bin2hex($cipherText256);
OpenSSL encryption code for the same function:
$key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; $iv = 'aaaaaaaaaaaaaaaa'; $data = 'dataString';
$data = $data . str_repeat("\x00", 16 - (strlen($data) % 16)); // 双引号可以解析asc-ii码\x00 return bin2hex(openssl_encrypt($data, "AES-256-CBC", $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv));
mcrypt uses padding
mcrypt encryption:
$key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; $iv = 'aaaaaaaaaaaaaaaa'; $data = 'dataString'; // 填充(移除填充反着移除即可) $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $pad = $block - (strlen($data) % $block); if ($pad <= $block) { $char = chr($pad); $data .= str_repeat($char, $pad); } $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); mcrypt_generic_init($cipher, $key, $iv); $cipherText256 = mcrypt_generic($cipher, $data); mcrypt_generic_deinit($cipher); return bin2hex($cipherText256);
openssl encryption code with the same function:
$key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; $iv = 'aaaaaaaaaaaaaaaa'; $data = 'dataString'; return bin2hex(openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv));
The above examples all run successfully, where the first example (without padding, but padding in openssl) and the second example (with padding, without padding in openssl) have the same output before and after replacement, and No compatibility issues. You can choose different replacement solutions based on the different filling methods of the code, but there are three details that need to be explained
Why is there filling?
Why are the names of the algorithms different after replacing them with openssl?
The next chapter will analyze the filling and algorithm in detail.
Padding
Why there is padding starts with the encryption algorithm. Because in the AES-128-CBC algorithm, the string to be encrypted will be segmented into segments every 16 bytes in length and calculated step by step, resulting in segments less than 16 bytes being filled. So there are two types of examples given: one is to use the default filling, and the other is to use independent filling. In the replacement with openssl, how to choose the padding scheme requires understanding of the default and autonomous padding of mcrypt and openssl.
mcrypt default filling
In the source code of php, it can be seen that the default filling is with \x00. In fact, it is not filled with \x00. From It can be found in the source code that a 16-bit empty string is first applied for, so each byte is \x00 during initialization. In fact, it can be said that there is no padding, but it is originally \x00, and the encryption obtained by using the default padding The string will be in the following form:
mcrypt is filled with
by default, so the redundant \ must be removed when decrypting. x00. Of course, you can also be lazy and not remove \x00. Because in php, the string "string\x00" and the string "string" have the same performance except for the length, so there seems to be no difference. The following code:
// 尾部包含若干个`\x00` 均可功输出true if ("string\x00" == "string") { // 用双引号可解析\x00 echo true; }
\x00 padded example: (Please pay attention to the length of the string, it can be seen that padding with \x00 will affect the length)
mcryptAutonomous filling
The filling algorithm needs to be carried out according to the following algorithm:
Add filling
/** * 填充算法 * @param string $source * @return string */ function addPKCS7Padding($source) { $source = trim($source); $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $pad = $block - (strlen($source) % $block); if ($pad <= $block) { $char = chr($pad); $source .= str_repeat($char, $pad); } return $source; }
After adding padding, the string actually looks like this:
Remove padding
/** * 移去填充算法 * @param string $source * @return string */ function stripPKSC7Padding($source) { $source = trim($source); $char = substr($source, -1); $num = ord($char); if ($num == 62) return $source; $source = substr($source, 0, -$num); return $source; }
openssl default filling
The default method is consistent with the standard mcrypt independent filling method, so in the second example, after using the above filling algorithm, openssl_encrypt can be used directly Replacement will not cause compatibility issues. The padded encrypted string is in the following form:
It should be noted that padding and padding removal are built-in in openssl_encrypt and openssl_decrypt, so you can use it directly unless you need to do it independently. Implement filling, otherwise there is no need to consider filling
openssl autonomous filling
openssl_encrypt provides option parameters to support independent filling, but after consulting the php source code, openssl The test case code found the correct usage:
// if we want to manage our own padding $padded_data = $data . str_repeat(' ', 16 - (strlen($data) % 16)); $encrypted = openssl_encrypt($padded_data, $method, $password, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv); $output = openssl_decrypt($encrypted, $method, $password, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv); var_dump(rtrim($output)); (备注:如上,OPENSSL_ZERO_PADDING 并非是为0填充的意思)
From this, we can explain the reason why in the first example, the code of independent point charging\x00 was added before openssl_encrypt
From the above encryption and decryption, the filling logic is different, for the above The example can be well explained:
Example 1:
mcrypt does not use padding when encrypting, so it is padded with \x00, so when replacing it with openssl, you need to implement \x00 padding independently. .
Example 2:
mcrypt uses standard padding when encrypting, and openssl's padding method is also standard padding, so you can use it directly.
After analyzing this, we can find that no matter what the padding strategy is, we need to pay attention to adding padding during encryption and removing padding during decryption. At this point, the filling-related analysis in the above example is completed. Next, let's look at how to choose the replaced algorithm.
Select algorithm
In the above example, there is a problem that the AES-128-CBC algorithm in mcrypt is not used in openssl How to replace it with AES_256?
Regarding this point, I haven’t found a reasonable explanation. I checked the source code for a while and couldn’t find the reason (the ability is limited~), but through the following information, the function was still completed
openssl Decrypt mcrypt AES data incompatibility problem
Convert mcrypt_generic to openssl_encrypt Ask Question
If any students find the reason, please leave me a message, thank you.
Summary
For the encryption part using mcrypt AES, if there is a problem during the replacement process, you can replace or fill in the two from the algorithm Let’s start thinking about it. At the same time, one of the conditions that must be met is to choose according to different filling methods. The most important thing to consider when replacing is to ensure that no changes will occur after replacement. Although there is only a slight difference - the difference in the last few strings, it is troublesome to modify it on multiple platforms at the same time, but the fewer changes, the smaller the risk.
This article only briefly explains the AES algorithm. Whether other algorithms are applicable remains to be studied.
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
PHP implementation of saving Canvas images in HTML5 to the server
Example analysis of multi-image upload function implemented by Laravel framework Blob
The above is the detailed content of Introduction to using openssl to replace mcrypt in PHP7.1. For more information, please follow other related articles on the PHP Chinese website!