How to decrypt data in Java that has been encrypted with PHP openssl_encryp aes-256-cbc method?

public static void main(String[] args) throws Exception {
    String iv = "0102030405060708";
    String key = "1882051051AgVfZUKJLInUbWvOPsAP6LM6nBwLn14140722186";

    byte[] aaa = AES_cbc_decrypt("hv208Otx0FZL32GUuErHDLlZzC3zVEGRt56f8lviQpk=", key, iv);
    System.out.println(new String(aaa));
}

private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

public static byte[] AES_cbc_decrypt(String content,String key,String iv) throws Exception 
{
    byte[] contentBytes = Base64.decode(content);
    byte[] keyBytes = key.substring(0, 16).getBytes();
    byte[] ivBytes = iv.getBytes();

    SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ivBytes));
    byte[] decbbdt = cipher.doFinal(contentBytes);
    return decbbdt;
}

      

run with this code and I get the following exception:

Exception on thread "main" javax.crypto.BadPaddingException: This final block is not filled correctly

it can be decrypted with php method

openssl_decrypt(base64_decode($encryptData), 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);

      

+3


source to share


1 answer


You are trying to decrypt a 16 byte or 128 bit key. However, you are using AES-256, where 256 stands for the key size: 32 bytes of course.

Now C and C libraries like OpenSSL usually use pointer arithmetic to determine the number of bytes. When specifying a key, they usually take a pointer address and a number of bytes (or for lower-level libraries, 32-bit words, etc.).

So when defining a key larger than 32 characters / bytes, that key is truncated to 32 bytes (or char

in C, where bytes and characters are forever confused). However, in Java code, you shorten the key to 16 bytes. This will result in AES-256 in C and AES-128 in Java.




Moral of the story: Don't confuse passwords / strings and keys.

0


source







All Articles