Solve the problem of inconsistent results of AES encryption in OpenSSL under C++/PHP

Recently, the company needs to use the AES algorithm to encrypt and transmit data. The client uses C/C++ development, and the web terminal uses PHP development.

The C/C++ side uses the OpenSSL library to implement AES encryption, and the PHP side uses the built-in openssl_encrypt to implement AES encryption. It was very smooth at the beginning, but when the connection was made later, it was found that the encrypted results from both sides were inconsistent, but the keys on both sides were the same as The initial vectors are all the same.

After repeated tests, it is found that when the plaintext is exactly a multiple of 16 bytes, the ciphertexts encrypted on both sides are consistent. Finally, I searched the Internet for information and found that when OpenSSL performs AES encryption, it can only encrypt 16 bytes at a time, so the length of the plaintext must be an integer multiple of 16, or at least greater than the minimum multiple of 16 of the length of in, so that encryption and decryption can be truly completed. . And if the plaintext length is not a multiple of 16, then the last few bytes are actually equivalent to padding \0.

Now that the cause of the problem is found, it is easy to handle. It is only necessary for PHP to judge the length of the plaintext before encryption. If the length is not a multiple of 16, it will automatically fill in \0 to a multiple of 16. For example, if the length is 15, it will be padded to 16, 30 will be padded to 32, and so on. Below is my autocomplete code:

<?php
$text = "12345678";
$text_len = strlen($text);
$mod = $text_len%16;
if($mod){
  $max = $text_len + (16 - $mod);
  for($i=$text_len;$i<$max;$i++){
    $text[$i] = "\0";
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324444682&siteId=291194637