What is the method for encrypting with AES in PHP?

In PHP, the openssl library can be used to implement AES encryption.

Here is an example code using the openssl library to perform AES encryption.

<?php
function encrypt($data, $key, $iv) {
    $ciphertext = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return base64_encode($ciphertext);
}

function decrypt($data, $key, $iv) {
    $ciphertext = base64_decode($data);
    return openssl_decrypt($ciphertext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
}

$data = 'Hello, World!';
$key = '0123456789abcdef';
$iv = 'fedcba9876543210';

$encrypted = encrypt($data, $key, $iv);
echo 'Encrypted: ' . $encrypted . "\n";

$decrypted = decrypt($encrypted, $key, $iv);
echo 'Decrypted: ' . $decrypted . "\n";
?>

In the above code, the encrypt function encrypts data using the openssl_encrypt function with AES encryption, and then converts the encrypted data to a readable string using the base64_encode function. The decrypt function decrypts the encrypted data by first converting the encrypted string back to binary data using the base64_decode function, and then decrypting it using the openssl_decrypt function.

Please note that the AES-128 algorithm and CBC mode are used in the examples above, you can adjust the parameters of the openssl_encrypt and openssl_decrypt functions if you need to use a different algorithm or mode.

At the same time, make sure that the OpenSSL extension is installed, or else the above code cannot be used.

bannerAds