0

I have this method here in a class named Buffers:

private static BufferedImage load(String s){
    BufferedImage image;
            try{
                image = ImageIO.read(Buffers.class.getResourceAsStream(s));
                return image;
            }catch(Exception e){
                e.printStackTrace();
            }
            return null;
}

That all the graphic contents in the project uses to load up the images. Example:

public static BufferedImage background = load("/path/");

I want to know if there is a way to only load encrypted images and then be decrypted only when called by this method.

If there is any doubt about what I'm trying to ask, please let me know.

Thank you!

Dormin
  • 23
  • 1
  • 6
  • The problem is that you'll have a hard time hiding the decryption key. If it's anywhere in that Jar, people can find it and use it to decrypt your images. – RealSkeptic Mar 01 '17 at 17:01
  • @RealSkeptic but I'm going to obfuscate the Jar file to difficult the acess to the key... I'm not trying to make it impossible to decrypt. – Dormin Mar 01 '17 at 17:08

1 Answers1

1

A way to have encrypted file is to use CipherInputStream and CipherOutputStream:

private BufferedImage load(String s){
BufferedImage image;
        try{
            image = ImageIO.read(getDecryptedStream(Buffers.class.getResourceAsStream(s)));
            return image;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
}

private InputStream getDecryptedStream(InputStream inputStream) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, this.key);
    CipherInputStream input = new CipherInputStream(inputStream, cipher);

    return input;
}

Use the outputStream to save the file

private OutputStream getEncryptedStream(OutputStream ouputStream) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException{
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, this.key);
    CipherOutputStream output = new CipherOutputStream(ouputStream, cipher);

    return output;
}
Fabien Leborgne
  • 377
  • 1
  • 5