PHP AES加解密示例
<?php
// 加密函数
function encrypt($data, $key) {
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
return base64_encode($iv . $encrypted);
}
// 解密函数
function decrypt($data, $key) {
$data = base64_decode($data);
$iv = substr($data, 0, openssl_cipher_iv_length('aes-256-cbc'));
$data = substr($data, openssl_cipher_iv_length('aes-256-cbc'));
$decrypted = openssl_decrypt($data, 'aes-256-cbc', $key, 0, $iv);
return $decrypted;
}
// 使用示例
$key = 'your-256-bit-secret'; // 256位密钥
$plaintext = 'Hello, World!';
// 加密
$encrypted = encrypt($plaintext, $key);
echo "Encrypted: " . $encrypted . "\n";
// 解密
$decrypted = decrypt($encrypted, $key);
echo "Decrypted: " . $decrypted . "\n";
?>
这段代码提供了AES-256-CBC加密算法的加解密函数,并展示了如何使用这些函数进行数据加密和解密。在使用这些函数之前,请确保您的PHP环境已经启用了OpenSSL扩展。
评论已关闭