Current Location: Home> Latest Articles> Detailed PHP AES Encryption Tutorial with Example Code

Detailed PHP AES Encryption Tutorial with Example Code

gitbox 2025-07-22

What is AES Encryption?

AES encryption (Advanced Encryption Standard) is a widely used symmetric encryption algorithm that effectively protects sensitive data and information security. Many developers choose AES encryption in their projects to secure data transmission and storage. This article explains how to implement AES encryption in PHP and provides practical code examples and best practices.

Basic Process of AES Encryption in PHP

To use AES encryption in PHP, it is essential to ensure the environment supports the OpenSSL extension. The implementation mainly involves three steps: generating the key and initialization vector (IV), encrypting data, and decrypting data.

Generating the Key and Initialization Vector

AES encryption requires a key and an initialization vector. The key length can be 128, 192, or 256 bits, while the IV is typically 128 bits. The following function demonstrates how to generate them:

function generateKeyAndIV() {
    $key = openssl_random_pseudo_bytes(16); // 128-bit key
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-128-cbc')); // 128-bit IV
    return [$key, $iv];
}

Data Encryption

After generating the key and IV, you can call the OpenSSL function to perform AES encryption on the data. Example:

function encryptData($data, $key, $iv) {
    return openssl_encrypt($data, 'aes-128-cbc', $key, 0, $iv);
}

Data Decryption

The decryption process uses the same key and IV and calls the OpenSSL decryption function:

function decryptData($encryptedData, $key, $iv) {
    return openssl_decrypt($encryptedData, 'aes-128-cbc', $key, 0, $iv);
}

Complete Example Code

Below is a complete PHP example including key and IV generation, data encryption, and decryption:

list($key, $iv) = generateKeyAndIV();
$data = "Hello, World!";
$encryptedData = encryptData($data, $key, $iv);
$decryptedData = decryptData($encryptedData, $key, $iv);
echo "Original data: $data
";
echo "Encrypted data: $encryptedData
";
echo "Decrypted data: $decryptedData
";

Summary

Using PHP's OpenSSL extension to implement AES encryption is straightforward, with key and IV randomness being critical for security. Prioritizing data encryption during development adds an important layer of protection to your applications. Hopefully, this article's examples and explanations help you better understand and apply AES encryption.