以下是 PHP 实现 AES-CBC-PKCS5Padding 加密并进行 base64 转码的示例代码:
<?php function encrypt($data, $key, $iv) { // PKCS5Padding 补齐数据 $padding = 16 - (strlen($data) % 16); $data .= str_repeat(chr($padding), $padding); // 使用 CBC 模式加密 $encrypted = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv); // 进行 base64 编码 return base64_encode($encrypted); } function decrypt($encryptedData, $key, $iv) { // 进行 base64 解码 $encrypted = base64_decode($encryptedData); // 使用 CBC 模式解密 $decrypted = openssl_decrypt($encrypted, 'AES-128-CBC', $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv); // 去除 PKCS5Padding 补齐的数据 return substr($decrypted, 0, -ord(substr($decrypted,-1))); } // 测试 $data = 'Hello World'; $key = '1234567890123456'; // 16 bytes key $iv = '1234567890123456'; // 16 bytes iv $encryptedData = encrypt($data, $key, $iv); echo "Encrypted data: " . $encryptedData; $decryptedData = decrypt($encryptedData, $key, $iv); echo "\nDecrypted data: " . $decryptedData;