PHP AES加密
使用PHP内置的mcrypt扩展库可以轻松地实现AES加密。
php
<?php
function aes_encrypt($data, $key, $iv) {
$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($cipher, $key, $iv);
$encrypted = mcrypt_generic($cipher, $data);
mcrypt_generic_deinit($cipher);
mcrypt_module_close($cipher);
return base64_encode($encrypted);
}
$key = '1234567890abcdef';
$iv = 'fedcba0987654321';
$data = 'Hello World!';
$encrypted = aes_encrypt($data, $key, $iv);
echo $encrypted;
?>
PHP AES解密
使用PHP内置的mcrypt扩展库也可以轻松地实现AES解密。
php
<?php
function aes_decrypt($encrypted, $key, $iv) {
$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
mcrypt_generic_init($cipher, $key, $iv);
$decrypted = mdecrypt_generic($cipher, base64_decode($encrypted));
mcrypt_generic_deinit($cipher);
mcrypt_module_close($cipher);
return trim($decrypted);
}
$key = '1234567890abcdef';
$iv = 'fedcba0987654321';
$encrypted = 'jRd3dw8c5YX2w/oQvhFqfg==';
$decrypted = aes_decrypt($encrypted, $key, $iv);
echo $decrypted;
?>
以上就是PHP AES加解密的简单实现方法。需要注意的是,mcrypt扩展库已经在PHP7.2版本中被废弃,建议使用其他扩展库或者使用PHP7.2以上版本内置的openssl扩展库实现AES加解密。