Convert Java to PHP: encrypt AES/CBC/PKCS7Padding, key size: 32 bytes, iv: 16 bytes

Viewed 25

I'm trying to convert Java to PHP code: encrypt AES/CBC/PKCS7Padding, key size: 32 bytes.
Java code

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

String data = "XXX_TEST";
String initVector = "IvHo9h3E2sNvyiT7";
String key = "0k7XHeJkgcI5cHTKblq7lmeM71wlBXQG";

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");

IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(StandardCharsets.UTF_8));

byte[] keyArr = Base64.getDecoder().decode(key.getBytes());
SecretKeySpec sKeySpec = new SecretKeySpec(keyArr, "AES");

cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, iv);

byte[] output = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

String encryptedData = Base64.getEncoder().encodeToString(output);

after run this: encryptedData will be tY3OYnUgdUMoSlRCcYWLYg==


PHP:

$iv = 'IvHo9h3E2sNvyiT7'; //same with JAVA code(16 bytes)
$key = '0k7XHeJkgcI5cHTKblq7lmeM71wlBXQG';//same with JAVA code(32 bytes)

$encryptedData = openssl_encrypt($data, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
$encryptedData = base64_encode($encryptedData);

after run this: $encryptedData will be oRSm/Jg/sAsMSgE++Mw5IQ==

Question: How can I adjust PHP code to make it has same output as Java code(tY3OYnUgdUMoSlRCcYWLYg==)?
I'm using php8.1

2 Answers

The main problem is, that you perform a Base64 decoding of the key. Just use the bytes:

String data = "XXX_TEST";
String initVector = "IvHo9h3E2sNvyiT7";
String key = "0k7XHeJkgcI5cHTKblq7lmeM71wlBXQG";

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 

IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(StandardCharsets.UTF_8));
byte[] keyArr = key.getBytes();
SecretKeySpec sKeySpec = new SecretKeySpec(keyArr, "AES");
cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, iv);
byte[] output = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
String encryptedData = Base64.getEncoder().encodeToString(output);
System.out.println(encryptedData);

results in oRSm/Jg/sAsMSgE++Mw5IQ==. Couldn't try it with PKCS7Padding, please try it on your own.

I got it's working now. Java Base64 decode the key => result is 24 bytes.
In PHP, I also did base64_decode and change algo to AES-192(instead of 256)

$iv = 'IvHo9h3E2sNvyiT7'; //same with JAVA code(16 bytes)
$key = '0k7XHeJkgcI5cHTKblq7lmeM71wlBXQG';//same with JAVA code(32 bytes)
$key = base64_decode($key);

$encryptedData = openssl_encrypt($data, 'aes-192-cbc', $key, OPENSSL_RAW_DATA, $iv);
$encryptedData = base64_encode($encryptedData);```
Related