如何加密BufferedImage只能被程序读取?

时间:2017-03-01 16:36:46

标签: java encryption bufferedimage

我在这个名为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;
}

项目中的所有图形内容都用于加载图像。例如:

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

我想知道是否有办法只加载加密图像,然后只有在通过此方法调用时才能解密。

如果对我要问的问题有任何疑问,请告诉我。

谢谢!

1 个答案:

答案 0 :(得分:1)

获取加密文件的方法是使用CipherInputStreamCipherOutputStream

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;
}

使用outputStream保存文件

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;
}