How can PHP utilize the OpenSSL library for encryption and decryption tasks?
To utilize the OpenSSL library for encryption and decryption tasks in PHP, you can use the openssl_encrypt and openssl_decrypt functions provided by the library. These functions allow you to encrypt and decrypt data using various encryption algorithms and modes supported by OpenSSL.
// Encrypt data using OpenSSL
function encryptData($data, $key, $iv) {
return openssl_encrypt($data, 'AES-256-CBC', $key, 0, $iv);
}
// Decrypt data using OpenSSL
function decryptData($data, $key, $iv) {
return openssl_decrypt($data, 'AES-256-CBC', $key, 0, $iv);
}
// Example usage
$data = "Hello, World!";
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(16);
$encryptedData = encryptData($data, $key, $iv);
echo "Encrypted Data: " . $encryptedData . "\n";
$decryptedData = decryptData($encryptedData, $key, $iv);
echo "Decrypted Data: " . $decryptedData . "\n";
Keywords
Related Questions
- What are the potential pitfalls of using serialize() and unserialize() functions in PHP when storing data in a database?
- What are the potential pitfalls of using mktime, date, and strtotime functions in PHP for timestamp manipulation?
- How can developers ensure that their PHP scripts are not vulnerable to SQL injection attacks?