I'm trying to encrypt/decrypt strings in python and java using AES, and encryption result is same in both. The encryption works fine, but when i try to decrypt the string in java it shows me this error ( javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher ). In python it works fine. What is the problem with java decryption ?
private static String toHexString(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; ++i) {
String s = Integer.toHexString(data[i] & 0XFF);
buf.append((s.length() == 1) ? ("0" + s) : s);
}
return buf.toString();
}
public static String encrypt(String input, String key) {
byte[] crypted = null;
try {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey);
crypted = cipher.doFinal(input.getBytes());
final String encryptedString = toHexString(Base64.encodeBase64(crypted));
return encryptedString;
} catch (Exception e) {
System.out.println(e.toString());
}
return "";
}
public static String decrypt(String encrypted, String key) {
char[] ch= encrypted.toCharArray();
try {
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher2 = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher2.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] h =Hex.decodeHex(ch);
String de = new String(Base64.decodeBase64(cipher2.doFinal(Hex.decodeHex(ch))),"UTF-8");
return de;
} catch (Exception e) {
System.out.println(e.toString());
}
return null;
}
javax.crypto.IllegalBlockSizeException
means the the data to be decrypted is not the correct size, it must be a multiple of 16-bytes. 3. Provide test key, data and encrypted data. 3. Best bet guess is there is an encoding mis-match, see point 3 above. – zaph