PHP AES Encryption & Decryption Guide
In PHP, you can use the OpenSSL library to perform AES encryption and decryption. Here is an example code:
function aesEncrypt($data, $key, $iv) {
$encrypted = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($encrypted);
}
function aesDecrypt($encryptedData, $key, $iv) {
$decrypted = openssl_decrypt(base64_decode($encryptedData), 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
return $decrypted;
}
$key = '0123456789abcdef'; // 密钥,必须是16字节
$iv = '1234567890abcdef'; // 初始化向量,必须是16字节
$plainText = 'Hello, World!';
$encryptedData = aesEncrypt($plainText, $key, $iv);
echo 'Encrypted: ' . $encryptedData . "\n";
$decryptedData = aesDecrypt($encryptedData, $key, $iv);
echo 'Decrypted: ' . $decryptedData . "\n";
Please note that the key and initialization vector (IV) in the above code must both be strings of 16 bytes in length. In practice, please generate secure key and IV based on your specific circumstances.
Additionally, make sure that the openssl extension for PHP is enabled, you can confirm this by checking the php.ini file or running the phpinfo() function.