php实现aes加密
AES 加密实现方法
在 PHP 中实现 AES 加密可以使用 openssl_encrypt 函数。AES(Advanced Encryption Standard)是一种对称加密算法,支持不同的密钥长度(128、192、256 位)和加密模式(如 CBC、ECB 等)。
基本加密函数
function aesEncrypt($data, $key, $iv) {
$method = 'AES-256-CBC'; // 加密方法和模式
$options = OPENSSL_RAW_DATA;
$encrypted = openssl_encrypt($data, $method, $key, $options, $iv);
return base64_encode($encrypted); // 返回 Base64 编码的加密数据
}
基本解密函数
function aesDecrypt($encryptedData, $key, $iv) {
$method = 'AES-256-CBC';
$options = OPENSSL_RAW_DATA;
$decrypted = openssl_decrypt(base64_decode($encryptedData), $method, $key, $options, $iv);
return $decrypted;
}
使用示例
$key = 'your-secret-key-32-bytes-long'; // 密钥长度必须符合所选 AES 版本(如 AES-256 需要 32 字节)
$iv = 'initialization-vector'; // 初始化向量(IV),通常为 16 字节
$data = 'Hello, AES Encryption!';
$encrypted = aesEncrypt($data, $key, $iv);
echo "Encrypted: " . $encrypted . "\n";
$decrypted = aesDecrypt($encrypted, $key, $iv);
echo "Decrypted: " . $decrypted . "\n";
密钥和 IV 生成
为了增强安全性,建议使用随机生成的密钥和 IV。
生成随机密钥和 IV
$key = openssl_random_pseudo_bytes(32); // 32 字节密钥(AES-256)
$iv = openssl_random_pseudo_bytes(16); // 16 字节 IV
注意事项
- 密钥长度必须与 AES 版本匹配:AES-128 需要 16 字节密钥,AES-192 需要 24 字节密钥,AES-256 需要 32 字节密钥。
- IV 长度通常为 16 字节(128 位),且每次加密时应使用不同的 IV。
- 存储或传输密钥和 IV 时需确保安全,避免泄露。
通过以上方法,可以在 PHP 中轻松实现 AES 加密和解密功能。







