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.
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.
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];
}
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);
}
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);
}
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
";
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.