How can PHP developers ensure that encrypted data can only be decrypted by authorized users with the correct keys?
To ensure that encrypted data can only be decrypted by authorized users with the correct keys, PHP developers can implement a system where the encryption key is securely stored and only accessible to authorized users. This can be done by using asymmetric encryption, where each user has their own public-private key pair. The data can be encrypted with the user's public key, and only the corresponding private key can decrypt it.
// Example code for encrypting data with a user's public key and decrypting with their private key
// Generate key pair for user
$privateKey = openssl_pkey_new();
openssl_pkey_export($privateKey, $privateKeyPEM);
$publicKey = openssl_pkey_get_details($privateKey)['key'];
// Encrypt data with user's public key
$data = "Sensitive data";
openssl_public_encrypt($data, $encryptedData, $publicKey);
// Decrypt data with user's private key
openssl_private_decrypt($encryptedData, $decryptedData, $privateKey);
echo $decryptedData; // Output: Sensitive data