Unable to decrypt encrypted file in android lollipop

I have an encryption / decryption mechanism for uploaded files in my application.

This mechanism works in all Android devices and versions up to version 5.0-lollipop.

Here is the decryption process:

cipher.init(Cipher.DECRYPT_MODE, key); fileInputStream = new FileInputStream(file); cipherInputStream = new CipherInputStream(fileInputStream, cipher); byte[] fileByte = new byte[(int) file.length()]; int j = cipherInputStream.read(fileByte); return fileByte; 

the cipher and key were created earlier and are used in the whole application:

  key = new SecretKeySpec(keyValue, "AES"); try { cipher = Cipher.getInstance("AES"); } catch (Exception e) { e.printStackTrace(); } 

When I decrypt a file of about 200,000 bytes in android 5.0, j (variable before returning) is about 8000, which is much lower than 200000, and in older versions for Android it is exactly equal to the decrypted file length.

I found that the problem is decryption. Because I can encrypt the file in android 5.0 and decrypt it in older versions of Android, but not vice versa. However, I am sending the encryption process:

 cipher.init(Cipher.ENCRYPT_MODE, AESutil.key); cipherOutputStream = new CipherOutputStream(output, cipher); byte data[] = new byte[1024]; int count; while ((count = input.read(data)) != -1) { cipherOutputStream.write(data, 0, count); } 

Thanks in advance

+5
source share
1 answer

Example My Cipher (L):

APPPATH is a line in my application directory on the SD card

 static void encrypt(File file, String pass) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(APPPATH+"/E_"+file.getName()); SecretKeySpec sks = new SecretKeySpec(pass.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); CipherOutputStream cos = new CipherOutputStream(fos, cipher); int b; byte[] d = new byte[8]; while((b = fis.read(d)) != -1) { cos.write(d, 0, b); } cos.flush(); cos.close(); fis.close(); } static void decrypt(File file, String pass) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(APPPATH+"/D_"+file.getName()); SecretKeySpec sks = new SecretKeySpec(pass.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); CipherInputStream cis = new CipherInputStream(fis, cipher); int b; byte[] d = new byte[8]; while((b = cis.read(d)) != -1) { fos.write(d, 0, b); } fos.flush(); fos.close(); cis.close(); } 
+2
source

Source: https://habr.com/ru/post/1210557/


All Articles