I'm trying to encrypt and decrypt image in Java using DESede algorithm. My approach to do that is by getting the pixels byte from BufferedImage and encrypt them, and then set the data element of WriteableRaster from the encrypted byte, finally save it to file. With the same approach at decrypting byte, I'm getting error because when I set data element of the raster, the encrypted image still in same size/height with first plain image. These are my codes:
public byte[] encrypt(byte[] plainByte) {
byte[] encryptedByte = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
encryptedByte = cipher.doFinal(plainByte);
} catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
System.err.println(e);
JOptionPane.showMessageDialog(null, e.getMessage());
}
return encryptedByte;
}
Code for decrypting byte:
public byte[] decrypt(byte[] encryptedByte) {
byte[] decryptedByte = null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
decryptedByte = cipher.doFinal(encryptedByte);
} catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
System.err.println(e);
JOptionPane.showMessageDialog(null, e.getMessage());
}
return decryptedByte;
}
and this is my implementation at processing image:
String password = "12345";//will be hashed with MD5
triDes.setPassword(password);
//proses enkripsi
BufferedImage image = ImageIO.read(new File("tes.jpg"));
byte[] pixels = (byte[]) image.getRaster().getDataElements(0, 0, image.getWidth(), image.getHeight(), null);
byte[] encrypt = triDes.encrypt(pixels);
System.out.println(encrypt.length + " - " + pixels.length);
WritableRaster raster = Raster.createBandedRaster(DataBuffer.TYPE_BYTE, image.getWidth(), image.getHeight(), 3, new Point(0, 0));
raster.setDataElements(0, 0, image.getWidth(), image.getHeight(), encrypt);
image.setData(raster);
File outputfile = new File("enkripsi.jpg");
ImageIO.write(image, "jpg", outputfile);
//proses dekripsi
image = ImageIO.read(new File("enkripsi.jpg"));
pixels = (byte[]) image.getRaster().getDataElements(0, 0, image.getWidth(), image.getHeight(), null);
System.out.println(pixels.length);
byte[] decrypt = triDes.decrypt(pixels);
raster = Raster.createBandedRaster(DataBuffer.TYPE_BYTE, image.getWidth(), image.getHeight(), 3, new Point(0, 0));
raster.setDataElements(0, 0, image.getWidth(), image.getHeight(), decrypt);
image.setData(raster);
outputfile = new File("dekripsi.jpg");
ImageIO.write(image, "jpg", outputfile);
I'm sorry for my bad English. On my codes the, the plain pixel bytes length and the encrypted bytes length is not in the same size. When I read encrypted image's bytes has the same length with the plain's bytes. I suspect the mistake at saving process, maybe the encrypted bytes is trimmed when BufferedImage saved. If my supposition is correct, How to setDataElements of WritableRaster without specifying witdth and height of the image?