Search code examples
androidencryptionon-the-fly

android decrypt image on the fly


I'm trying to decrypt images on the fly in my application. I'm downloading them over internet and than I want to decrypt them and show 'em as backgrounds or in imageview. So my problem is that I can't figure it out how to make the whole logic.

For now I'm getting the images from sdcard by their path which is generated by a method i wrote :

    public static String getImagePathFromExternalStorage(String server, int userId, String filename){
        String path=Environment.getExternalStorageDirectory()
        + "/Documents/Users/"+server+"/"+userId+"/Storage/" + filename;

        return path;
    }

    public static String getImagePathFromInternalStorage(String server, int userId, String filename, Context context){
        String path = context.getFilesDir() + "/documents/users/"+server+"/"+userId+"/storage/"+filename;

        return path;
    }

And I'm decrypting images like this :

Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
ByteArrayInputStream input = new ByteArrayInputStream(mediaCollBuffer); 
CipherInputStream cis = new CipherInputStream(input, cipher);

So I'm trying to figure it out how to get the file by it's path, decrypt it on the fly and set it as background. Any suggestions?


Solution

  • Try this :

    File bufferFile = new File(path);
    FileInputStream fis   = new FileInputStream(bufferFile);
    
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
    IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    CipherInputStream cis = new CipherInputStream(fis, cipher);
    Bitmap ops = BitmapFactory.decodeStream(cis);
    logo.setImageBitmap(ops);
    

    I think this should help.