PHP AES加解密示例
一、概述
本示例演示了如何在PHP中使用AES算法进行加解密操作。
二、环境准备
PHP 7.4
OpenSSL扩展
三、示例代码
function encrypt($plaintext, $key, $iv)
{
$method = 'aes-256-cbc';
$options = OPENSSL_RAW_DATA;
$ciphertext = openssl_encrypt($plaintext, $method, $key, $options, $iv);
return base64_encode($ciphertext);
}
Use code with caution.
function decrypt($ciphertext, $key, $iv)
{
$method = 'aes-256-cbc';
$options = OPENSSL_RAW_DATA;
$plaintext = openssl_decrypt(base64_decode($ciphertext), $method, $key, $options, $iv);
return $plaintext;
}
Use code with caution.
$plaintext = 'Hello, world!';
$key = '秘钥字符串,应该是16或32字节';
$iv = '初始化向量,16字节';
$ciphertext = encrypt($plaintext, $key, $iv);
echo 'Encrypted: ' . $ciphertext . "\n";
$decryptedText = decrypt($ciphertext, $key, $iv);
echo 'Decrypted: ' . $decryptedText . "\n";
Use code with caution.
四、运行结果
Decrypted: Hello, world!
五、说明
加密函数使用openssl_encrypt函数进行加密,并使用base64_encode函数将密文进行编码。
解密函数使用openssl_decrypt函数进行解密,并使用base64_decode函数将密文进行解码。
六、注意事项
密钥和初始化向量应该是随机生成的,并保证安全性。
密钥和初始化向量需要与加密和解密函数保持一致。
七、其他示例
使用AES算法加密文件。
使用AES算法加密数据库连接信息。
八、总结
AES算法是一种常用的对称加密算法,具有较高的安全性。通过使用PHP中的AES加解密函数,可以有效地保护敏感数据安全。