4
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 follow exception :

Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded

it can be decrypt by php method

openssl_decrypt(base64_decode($encryptData), 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • 1
    Why reducing the key from 50 bytes to 16? AFAIK in php it is denoted as password not key, which means that that it can be of any length and a key derivation function is used for generating the real key. – Robert Jul 31 '17 at 16:15
  • You need to show your complete php code. It's not clear how key and IV are actually decoded. – Artjom B. Jul 31 '17 at 17:54
  • Never use `String#getBytes` without an argument, because the default character set might change between different systems. – Artjom B. Jul 31 '17 at 17:55

1 Answers1

1

You try to decrypt with a key of 16 bytes or 128 bits. However, you have been using AES-256 where 256 denotes the key size: 32 bytes of course.

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

So in all likelihood when specifying a key larger than 32 characters / bytes this key is cut down to 32 bytes (or chars in C, where bytes and characters are for ever confused). However in your Java code you cut down the key to 16 bytes. This would lead to using AES-256 in C and AES-128 in Java.


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

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263