What are some best practices for handling encryption and decryption of data in PHP, especially when working with multiple records?

When handling encryption and decryption of data in PHP, especially with multiple records, it is crucial to use a secure encryption algorithm and properly manage encryption keys. One best practice is to generate a unique encryption key for each record and securely store these keys. Additionally, consider using a secure method to transmit and store these keys, such as using a key management service.

// Example of encrypting and decrypting data using OpenSSL in PHP

// Generate a unique encryption key for each record
$encryptionKey = openssl_random_pseudo_bytes(32);

// Encrypt data using the encryption key
function encryptData($data, $encryptionKey) {
    $iv = openssl_random_pseudo_bytes(16);
    $encrypted = openssl_encrypt($data, 'AES-256-CBC', $encryptionKey, 0, $iv);
    return base64_encode($iv . $encrypted);
}

// Decrypt data using the encryption key
function decryptData($data, $encryptionKey) {
    $data = base64_decode($data);
    $iv = substr($data, 0, 16);
    $encrypted = substr($data, 16);
    return openssl_decrypt($encrypted, 'AES-256-CBC', $encryptionKey, 0, $iv);
}

// Usage example
$data = "Sensitive data to encrypt";
$encryptedData = encryptData($data, $encryptionKey);
echo "Encrypted data: " . $encryptedData . "\n";
$decryptedData = decryptData($encryptedData, $encryptionKey);
echo "Decrypted data: " . $decryptedData . "\n";