Reputation: 49
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);
Upvotes: 4
Views: 181
Reputation: 93968
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 char
s 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.
Upvotes: 1