AES Encryption and Decryption Encapsulation Class and Usage Example Implemented by PHP

  • 2021-10-25 06:17:20
  • OfStack

This paper describes the AES encryption and decryption encapsulation class and its usage realized by PHP. Share it for your reference, as follows:


<?php
/**
 * Class AES
 *  Used for AES Encrypt and decrypt data 
 * time:2018-04-27
 */
class AES
{
  protected $cipher = MCRYPT_RIJNDAEL_256; //AES Encryption algorithm 
  protected $mode = MCRYPT_MODE_CBC; // Adopt cbc Encryption mode 
  protected $key; // Key 
  protected $iv; //cbc Mode encryption vector, if it is empty, it will be replaced by key 
  /**
   * AES constructor.
   *
   * @param   $key  Key 
   * @param null $iv  Vector   Optional   If it is empty, the key will be used instead 
   *
   * @throws Exception
   */
  public function __construct($key, $iv = NULL)
  {
    if (!extension_loaded("mcrypt")) {
//      throw new \Exception("mcrypt extension do not exist. it was DEPRECATED in PHP 7.1.0, and REMOVED in PHP 7.2.0. use OpenSSL instead");
    }
    $this->key = $key;
    $this->iv = $iv;
  }
  /**
   *  Encrypted data 
   * @param $data
   *
   * @return string
   */
  public function encrypt($data)
  {
    $td = mcrypt_module_open($this->cipher, '', $this->mode, '');
    $key = hash("sha256", $this->key, true);
    $iv = isset($this->iv) ? hash("sha256", $this->iv, true) : $key;
    $data = $this->padding($data);
    mcrypt_generic_init($td, $key, $iv);
    $encryptedData = base64_encode(mcrypt_generic($td, $data));
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $encryptedData;
  }
  /**
   *  Decrypt data 
   * @param $data
   *
   * @return bool|string
   */
  public function decrypt($data)
  {
    $td = mcrypt_module_open($this->cipher, '', $this->mode, '');
    $key = hash("sha256", $this->key, true);
    $iv = isset($this->iv) ? hash("sha256", $this->iv, true) : $key;
    mcrypt_generic_init($td, $key, $iv);
    $decrypted_data = mdecrypt_generic($td, base64_decode($data));
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $this->unPadding($decrypted_data);
  }
  /**
   *  Padding data to an integer multiple of the packet size 
   * @param null $data
   *
   * @return string
   */
  protected function padding($data = null)
  {
    $blockSize = 32; //MCRYPT_RIJNDAEL_256 The packet size of the algorithm is 32 Byte 
    $pad = $blockSize - (strlen($data) % $blockSize);
    return $data . str_repeat(chr($pad), $pad);
  }
  /**
   *  Remove populated data 
   * @param null $data
   *
   * @return bool|string
   */
  protected function unPadding($data = null)
  {
    $pad = ord($data[strlen($data) - 1]);
    if ($pad > strlen($data)) {
      return false;
    }
    if (strspn($data, chr($pad), strlen($data) - $pad) != $pad) {
      return false;
    }
    return substr($data, 0, -1 * $pad);
  }
  /**
   * @return mixed
   */
  public function getSecretKey()
  {
    return $this->key;
  }
  /**
   * @param mixed $key
   */
  public function setSecretKey($key)
  {
    $this->key = $key;
  }
  /**
   * @return null
   */
  public function getIv()
  {
    return $this->iv;
  }
  /**
   * @param null $iv
   */
  public function setIv($iv)
  {
    $this->iv = $iv;
  }
}
// Usage: 
$keyStr = 'sq8f77fwhksk';
$aes = new AES($keyStr);
$str = 'www.ofstack.com';
$chgstr = $aes->encrypt($str);
echo $chgstr;
echo "<br/>";
$rstr = $aes->decrypt($chgstr);
echo $rstr;
?>

Run results:

pDyiRRNaxlss2b6SgoiVPdkD2m1QWhX393lh2iFgGdY=
www.ofstack.com

PS: Friends who are interested in encryption and decryption can also refer to the online tools of this site:

Text online encryption and decryption tools (including AES, DES, RC4, etc.):
http://tools.ofstack.com/password/txt_encode

MD5 Online Encryption Tool:
http://tools.ofstack.com/password/CreateMD5Password

Online hash/hash algorithm encryption tool:
http://tools.ofstack.com/password/hash_encrypt

Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 Encryption Tool:
http://tools.ofstack.com/password/hash_md5_sha

Online sha1/sha224/sha256/sha384/sha512 Encryption Tool:
http://tools.ofstack.com/password/sha_encode

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of php Encryption Methods", "Summary of PHP Encoding and Transcoding Operation Skills", "Summary of PHP Mathematical Operation Skills", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Tutorial on PHP Data Structure and Algorithm", "Summary of php Programming Algorithm" and "Summary of php Regular Expression Usage"

I hope this article is helpful to everyone's PHP programming.


Related articles: