要将PKCS5填充的Java AES - CBC更改为PHP,需要进行以下步骤:
下面是一个示例代码,演示了如何将Java AES - CBC的PKCS5填充方式更改为PHP:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
String key = "0123456789abcdef";
String iv = "fedcba9876543210";
// Encrypt
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Encrypted Text: " + encryptedText);
// Decrypt
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
String decryptedText = new String(decryptedBytes);
System.out.println("Decrypted Text: " + decryptedText);
}
}
function encrypt($plainText, $key, $iv) {
$encryptedText = openssl_encrypt($plainText, 'AES-256-CBC', base64_decode($key), OPENSSL_RAW_DATA, hex2bin($iv));
return base64_encode($encryptedText);
}
function decrypt($encryptedText, $key, $iv) {
$decryptedText = openssl_decrypt(base64_decode($encryptedText), 'AES-256-CBC', base64_decode($key), OPENSSL_RAW_DATA, hex2bin($iv));
return $decryptedText;
}
$plainText = "Hello, World!";
$key = "0123456789abcdef";
$iv = "fedcba9876543210";
$encryptedText = encrypt($plainText, $key, $iv);
echo "Encrypted Text: " . $encryptedText . "\n";
$decryptedText = decrypt($encryptedText, $key, $iv);
echo "Decrypted Text: " . $decryptedText . "\n";
在这个示例中,$key和$iv是Base64编码的字符串,可以根据具体需求进行调整。另外,还可以根据需要添加错误处理和输入验证的逻辑。
对于相关的产品和文档链接,请参考腾讯云的官方文档:
领取专属 10元无门槛券
手把手带您无忧上云