php实现aes

PHP 实现 AES 加密解密
PHP 提供了 openssl_encrypt 和 openssl_decrypt 函数来实现 AES 加密和解密。以下是常见的 AES 加密模式(如 AES-256-CBC)的实现方法。
AES 加密
function encryptAES($data, $key, $iv) {
$method = 'aes-256-cbc';
$encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($encrypted);
}
AES 解密
function decryptAES($encryptedData, $key, $iv) {
$method = 'aes-256-cbc';
$decrypted = openssl_decrypt(base64_decode($encryptedData), $method, $key, OPENSSL_RAW_DATA, $iv);
return $decrypted;
}
使用示例
$key = 'your-32-byte-encryption-key-here'; // 32 字节密钥(AES-256)
$iv = 'your-16-byte-iv-here'; // 16 字节初始化向量(IV)
$plaintext = "Hello, AES!";
$encrypted = encryptAES($plaintext, $key, $iv);
$decrypted = decryptAES($encrypted, $key, $iv);
echo "Plaintext: " . $plaintext . "\n";
echo "Encrypted: " . $encrypted . "\n";
echo "Decrypted: " . $decrypted . "\n";
注意事项
- 密钥长度:AES-256 需要 32 字节密钥,AES-192 需要 24 字节,AES-128 需要 16 字节。
- IV 长度:初始化向量(IV)必须为 16 字节,且每次加密应使用不同的 IV。
- 安全存储:密钥和 IV 应安全存储,避免硬编码在代码中。
- 错误处理:实际使用时需添加错误检查逻辑。







