I have this test code:
byte[] aesPass1 = { (byte) 204, (byte) 204, (byte) 204, (byte) 204, (byte) 204};
encrypted = encryptAES256("Anything".getBytes("UTF8"), new String(aesPass1, "UTF8"), salt, 1000, iv_b);
to encrypt some data, and this test code:
byte[] aesPass1 = { (byte) 204, (byte) 204, (byte) 204, (byte) 204, (byte) 204};
decryptAES256(encrypted, new String(aesPass1, "UTF8"), salt, 100, iv_b);
to decrypt data.
If I encrypt on Android 4.4.4 I can decrypt on the same device (Android 4.4.4) with no problems, but if I try to decrypt on Android 4.2.2 I get "pad block corrupted" error.
Similar, if I encrypt on Android 4.2.2 I can decrypt on the same device (Android 4.2.2) with no problems, but on Android 4.4.4 I get "error06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt" error.
To make this even stranger for me, if I use this code:
encrypted = encryptAES256("Anything".getBytes("UTF8"), "pass", salt, 1000, iv_b);
to encrypt, and:
decryptAES256(encrypted, "pass", salt, 100, iv_b);
everything works fine on both Android 4.2.2 and Android 4.4.4.
The only difference I can see is using new String(aesPass1, "UTF8") fuction.
My encrypt and decrypt functions:
public static byte[] encryptAES256(byte[] data, String passphrase, byte[] salt, int iterations, byte[] ivbytes) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec specKey = new PBEKeySpec(passphrase.toCharArray(), salt, iterations, 256);
SecretKey secretKey = factory.generateSecret(specKey);
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(ivbytes));
return cipher.doFinal(data);
}
public static byte[] decryptAES256(byte[] data, String passphrase, byte[] salt, int iterations, byte[] ivbytes) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec specKey = new PBEKeySpec(passphrase.toCharArray(), salt, iterations, 256);
SecretKey secretKey = factory.generateSecret(specKey);
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivbytes));
return cipher.doFinal(data);
}
Can you help?
Thank you in advance!