Current Location: Home> Latest Articles> Complete Guide to AES Encryption and Decryption in PHP

Complete Guide to AES Encryption and Decryption in PHP

gitbox 2025-07-26

Introduction to the AES Encryption Algorithm

AES (Advanced Encryption Standard) is a widely-used symmetric encryption algorithm. It was officially released in 2001 by the National Institute of Standards and Technology (NIST) to replace the less secure DES (Data Encryption Standard).

AES applies multiple rounds of transformations, including substitution, permutation, and mixing, to encrypt data. It supports key sizes of 128, 192, and 256 bits. With its efficiency, security, and cross-platform compatibility, AES has become a dominant encryption standard in modern cryptography.

Integrating AES in PHP

To implement AES encryption in PHP, it is recommended to use the Defuse\Crypto library. This library is simple, robust, and widely adopted in secure PHP applications.

Installing the Defuse Encryption Library

Start by installing the Defuse Encryption library via Composer:

composer require defuse/php-encryption

Encrypting Data with AES in PHP

Once installed, you can encrypt data using the library as follows:

$key = 'your_secret_key';
$aes = new Defuse\Crypto\Key($key);
$data = 'your_data';
$encryptedData = $aes->encrypt($data);

This code securely encrypts $data and stores the result in $encryptedData.

Decrypting Data

To retrieve the original data from the encrypted string, use the same object and decryption method:

$decryptedData = $aes->decrypt($encryptedData);

This decrypts $encryptedData back to its original form.

Complete PHP Code Example

The following is a full example demonstrating AES encryption and decryption in PHP:

// Install the AES library
composer require defuse/php-encryption

// Encrypt data
$key = 'your_secret_key';
$aes = new Defuse\Crypto\Key($key);
$data = 'your_data';
$encryptedData = $aes->encrypt($data);

// Decrypt data
$decryptedData = $aes->decrypt($encryptedData);

echo "Original Data: " . $data;
echo "Encrypted Data: " . $encryptedData;
echo "Decrypted Data: " . $decryptedData;

Make sure the $key is a secure 16- or 32-character string. Avoid hardcoding it in your application; instead, store it in environment variables or secure configuration files.

Conclusion

AES encryption offers a reliable and efficient way to protect sensitive information. In PHP, using well-established libraries like Defuse allows you to implement encryption and decryption with minimal risk and high security.

In real-world applications, always protect your encryption keys and implement proper data validation and storage practices to maintain overall data security.