What are some alternatives to mcrypt_decrypt and mcrypt_encrypt for encrypting data in PHP?
The mcrypt extension in PHP has been deprecated since PHP 7.1 and removed in PHP 7.2. To encrypt and decrypt data in PHP without using mcrypt, you can use the openssl extension or the sodium extension. These alternatives provide modern and secure encryption methods.
// Using openssl_encrypt and openssl_decrypt for encryption and decryption
function encryptData($data, $key){
$cipher = "aes-256-cbc";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$encrypted = openssl_encrypt($data, $cipher, $key, 0, $iv);
return base64_encode($iv . $encrypted);
}
function decryptData($data, $key){
$cipher = "aes-256-cbc";
$ivlen = openssl_cipher_iv_length($cipher);
$data = base64_decode($data);
$iv = substr($data, 0, $ivlen);
$data = substr($data, $ivlen);
return openssl_decrypt($data, $cipher, $key, 0, $iv);
}
// Example usage
$data = "Hello, World!";
$key = "secretkey";
$encryptedData = encryptData($data, $key);
echo "Encrypted data: " . $encryptedData . "\n";
$decryptedData = decryptData($encryptedData, $key);
echo "Decrypted data: " . $decryptedData;