What is the recommended approach for securely encrypting data in PHP using AES?
To securely encrypt data in PHP using AES, it is recommended to use the openssl_encrypt function with a secure encryption algorithm, such as AES-256-CBC, and a strong encryption key and initialization vector (IV). It is important to store the encryption key and IV securely and never expose them in the code or store them alongside the encrypted data.
function encryptData($data, $key, $iv) {
$cipher = "aes-256-cbc";
$encrypted = openssl_encrypt($data, $cipher, $key, 0, $iv);
return base64_encode($encrypted);
}
function decryptData($data, $key, $iv) {
$cipher = "aes-256-cbc";
$decrypted = openssl_decrypt(base64_decode($data), $cipher, $key, 0, $iv);
return $decrypted;
}
// Example usage
$data = "Sensitive data to encrypt";
$key = random_bytes(32); // 256-bit encryption key
$iv = random_bytes(16); // 128-bit IV
$encryptedData = encryptData($data, $key, $iv);
echo "Encrypted Data: " . $encryptedData . "\n";
$decryptedData = decryptData($encryptedData, $key, $iv);
echo "Decrypted Data: " . $decryptedData . "\n";
Related questions
-
PHP JavaScript toggling elements
-
memory management performance optimization cron jobs
-
PHP external APIs ripe.net