上代码
class AES {
private $key;
private $iv;
public function __construct($key, $iv) {
$this->key = $key;
$this->iv = $iv;
}
public function encrypt($data) {
$encrypted = openssl_encrypt($data, 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
return base64_encode($encrypted);
}
public function decrypt($encryptedData) {
$decrypted = openssl_decrypt(base64_decode($encryptedData), 'AES-128-ECB', $this->key, OPENSSL_RAW_DATA);
return $decrypted;
}
public function encryptCBC($data) {
$encrypted = openssl_encrypt($data, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv);
return base64_encode($encrypted);
}
public function decryptCBC($encryptedData) {
$decrypted = openssl_decrypt(base64_decode($encryptedData), 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv);
return $decrypted;
}
}
// 使用示例:
$key = '0123456789abcdef'; // 16字节长度的密钥
$iv = 'fedcba9876543210'; // 16字节长度的初始向量
$aes = new AES($key, $iv);
$data = 'Hello, World!';
$encryptedECB = $aes->encrypt($data);
echo 'AES-128-ECB加密后的数据:' . $encryptedECB . "\n";
$decryptedECB = $aes->decrypt($encryptedECB);
echo 'AES-128-ECB解密后的数据:' . $decryptedECB . "\n";
$encryptedCBC = $aes->encryptCBC($data);
echo 'AES-256-CBC加密后的数据:' . $encryptedCBC . "\n";
$decryptedCBC = $aes->decryptCBC($encryptedCBC);
echo 'AES-256-CBC解密后的数据:' . $decryptedCBC . "\n";