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加密算法的加解密函数,并展示了如何使用这些函数进行数据加密和解密。在实际应用中,应该使用强随机密钥,并确保其安全传输。
评论已关闭