What are best practices for handling sensitive data encryption in PHP projects?

Sensitive data encryption in PHP projects should follow best practices to ensure data security. One common approach is to use a strong encryption algorithm like AES with a secure key management system. It's also important to securely store the encryption keys and never hardcode them in the code.

// Generate a secure encryption key
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);

// Encrypt sensitive data using AES encryption
function encryptData($data, $key) {
    $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    $cipherText = sodium_crypto_secretbox($data, $nonce, $key);
    return base64_encode($nonce . $cipherText);
}

// Decrypt sensitive data
function decryptData($encryptedData, $key) {
    $decoded = base64_decode($encryptedData);
    $nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    $cipherText = substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    $decrypted = sodium_crypto_secretbox_open($cipherText, $nonce, $key);
    return $decrypted;
}

// Example usage
$encrypted = encryptData("sensitive data", $key);
$decrypted = decryptData($encrypted, $key);
echo $decrypted;