PHP AES Encryption and Decryption Using OpenSSL
This article demonstrates how to replace the deprecated mcrypt functions in PHP with OpenSSL by providing a compact Aes class that handles AES‑128‑CBC encryption and decryption, including configuration of key, IV, and method, and shows practical usage examples.
AES encryption in PHP5 used the mcrypt_decrypt function, which has been deprecated after PHP 7.1; the modern replacement is OpenSSL's openssl_encrypt and openssl_decrypt. The following compact class implements both operations.
<?php
class Aes {
public $key = '';
public $iv = '';
public function __construct($config) {
foreach ($config as $k => $v) {
$this->$k = $v;
}
}
// Encryption
public function aesEn($data) {
return base64_encode(openssl_encrypt($data, $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv));
}
// Decryption
public function aesDe($data) {
return openssl_decrypt(base64_decode($data), $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
}
}
?>The class is configured with an associative array specifying the encryption key, a 16‑byte IV generated via md5(time().uniqid(), true), and the method (e.g., 'AES-128-CBC').
<?php
$config = [
// encryption key
'key' => 'aaaabbbbcccc',
// ensure IV is 16 bytes
'iv' => md5(time().uniqid(), true),
// encryption method
'method' => 'AES-128-CBC',
];
$obj = new Aes($config);
$res = $obj->aesEn('123456789');
// encrypted data
echo $res;
?>To decrypt, instantiate the class with the same configuration and call aesDe on the encrypted string.
<?php
$obj = new Aes($config);
$decrypted = $obj->aesDe($res);
echo $decrypted; // outputs original data
?>This approach allows developers to hide sensitive parameters and data by encrypting them before transmission, ensuring that only the backend can decrypt and process the original information.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
