How can I use openssl_decrypt as a JAVA?

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

Here is PHP code

    $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.



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.

Leave a Reply

Your email address will not be published. Required fields are marked *