1

I would like to know that How can I use openssl_decrypt in JAVA?

Here is PHP code

<?php
    $textToDecrypt = hex2bin("db3700cd861aee8215b3db514adde6c9"); // input is hexadecimal format
    $key = "MbQeThWmZq4t7w1z";
    $decrypted = openssl_decrypt($textToDecrypt, 'AES-128-CBC', $aesKey, OPENSSL_NO_PADDING);
    echo "decrypt data is ". $decrypted
?>

And here is my JAVA code

byte[] textToDecrypt = inp.getBytes();

SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");

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

cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);


byte[] original = cipher.doFinal(textToDecrypt);

result = new String((original));

The PHP code can decrypt correctly but in JAVA I got the error "Parameters missing"

How can I solve this.

Thanks.

Pim H
  • 223
  • 2
  • 8
  • In the PHP code the IV is missing (CBC always uses an IV). I guess that PHP then implicitly takes a 0-vector (all 16 bytes are 0x00), at least for decryption. But in the Java code the IV must be set _explicitly_ using [`IvParameterSpec`](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/javax/crypto/spec/IvParameterSpec.html). This is missing. – Topaco Mar 22 '21 at 08:26
  • Hi Topaco, I have added IvParameterSpec iv = new IvParameterSpec(encrypted, 0, 16) and edit the init function to cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv); but it's not decrypt correctly – Pim H Mar 22 '21 at 08:29
  • Why do you use the first 16 bytes of `encrypted` for the IV? I don't see nothing like that in the PHP code. Did you test a 0-vector for the IV? – Topaco Mar 22 '21 at 08:35
  • Because i'm not sure how to add it. I have decalre the iv as a 0000000000000000 and use with IvParameterSpec but the result is like ?Dฤญ3L”Mๆ(ฬฺฺ๔|ฎฝม?ส Uด/A`\. maybe I missing something in the decryption step – Pim H Mar 22 '21 at 08:40
  • See my answer please. – Topaco Mar 22 '21 at 09:01

1 Answers1

1

The PHP code implicitly uses a zero IV, which must be explicitly set in the Java code. In addition, in the Java Code the ciphertext must be hex decoded, e.g.:

byte[] textToDecrypt = hexStringToByteArray("db3700cd861aee8215b3db514adde6c9");

SecretKeySpec secretKeySpec = new SecretKeySpec("MbQeThWmZq4t7w1z".getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(new byte[16]));

byte[] original = cipher.doFinal(textToDecrypt);
String result = new String(original, StandardCharsets.UTF_8);
System.out.println(result); // hellotest

where hexStringToByteArray() is from here.

Please note that a static IV is insecure.

Topaco
  • 40,594
  • 4
  • 35
  • 62