Replacement of AES encryption and decryption method mcrypt_module_open of in PHP 7.1

  • 2021-08-10 06:53:49
  • OfStack

Preface

The mcrypt extension has been obsolete for about 10 years and is complex to use. Therefore, it was abandoned and replaced by OpenSSL. It will be removed from the core code and moved to PECL as of PHP 7.2.

The PHP manual gives an alternative on the migration page 7.1, which is to replace MCrypt with OpenSSL.

Sample code


/**
 * [AesSecurity aes Encryption, support PHP7.1]
 */
class AesSecurity
{
 /**
  * [encrypt aes Encryption ]
  * @param [type]     $input [ Data to encrypt ]
  * @param [type]     $key [ Encryption key]
  * @return [type]       [ Encrypted data ]
  */
 public static function encrypt($input, $key)
 {
  $data = openssl_encrypt($input, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
  $data = base64_encode($data);
  return $data;
 }
 /**
  * [decrypt aes Decryption ]
  * @param [type]     $sStr [ Data to decrypt ]
  * @param [type]     $sKey [ Encryption key]
  * @return [type]       [ Decrypted data ]
  */
 public static function decrypt($sStr, $sKey)
 {
  $decrypted = openssl_decrypt(base64_decode($sStr), 'AES-128-ECB', $sKey, OPENSSL_RAW_DATA);
  return $decrypted;
 }
}

It can be adapted according to needs.

Summarize


Related articles: