What is the significance of using AES encryption and Base64 encoding in PHP for storing data in a MySQL database?
When storing sensitive data in a MySQL database, it is important to encrypt the data to ensure its security. AES encryption is a widely used encryption algorithm that provides strong security for data. Base64 encoding is used to encode the encrypted data so that it can be safely stored in a text format in the database.
// Encrypt data using AES encryption
function encryptData($data, $key) {
$cipher = "aes-256-cbc";
$iv_length = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($iv_length);
$encrypted = openssl_encrypt($data, $cipher, $key, 0, $iv);
return base64_encode($iv . $encrypted);
}
// Decrypt data using AES encryption
function decryptData($data, $key) {
$cipher = "aes-256-cbc";
$iv_length = openssl_cipher_iv_length($cipher);
$data = base64_decode($data);
$iv = substr($data, 0, $iv_length);
$encrypted = substr($data, $iv_length);
return openssl_decrypt($encrypted, $cipher, $key, 0, $iv);
}
// Example usage
$key = "your_secret_key";
$data = "sensitive_data_to_encrypt";
$encryptedData = encryptData($data, $key);
echo "Encrypted data: " . $encryptedData . "\n";
$decryptedData = decryptData($encryptedData, $key);
echo "Decrypted data: " . $decryptedData;