使用 OpenSSL 扩展进行 AES 加密和解密
PHP的OpenSSL扩展提供了对AES加密的支持。以下是一个使用AES-256-CBC模式进行加密和解密的示例。
示例代码
<?php
function encrypt($plaintext, $key, $iv) {
// 确保密钥长度为32字节(256位)以用于AES-256
$key = substr(hash('sha256', $key, true), 0, 32);
// 使用OpenSSL进行加密
$ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
// 返回base64编码的密文
return base64_encode($ciphertext);
}
function decrypt($ciphertext, $key, $iv) {
// 确保密钥长度为32字节(256位)以用于AES-256
$key = substr(hash('sha256', $key, true), 0, 32);
// 解码base64编码的密文
$ciphertext = base64_decode($ciphertext);
// 使用OpenSSL进行解密
return openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
}
// 示例用法
$key = "thisisaverysecurekey12345"; // 密钥(建议至少32字节)
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); // 生成一个随机的IV
$plaintext = "Hello, World!";
echo "原文: $plaintext\n";
$ciphertext = encrypt($plaintext, $key, $iv);
echo "加密后: $ciphertext\n";
// 解密时需要使用相同的IV
$decryptedtext = decrypt($ciphertext, $key, $iv);
echo "解密后: $decryptedtext\n";
?>