我试图使用DESede算法在Java中加密和解密图像。 我的做法是通过从BufferedImage中获取像素字节并对它们进行加密,然后从加密字节中设置WriteableRaster的数据元素,最后将其保存到文件中。使用解密字节时的相同方法,我得到错误,因为当我设置栅格的数据元素时,加密的图像仍然与第一个普通图像具有相同的大小/高度。 这是我的代码:在Java中使用TripleDES加密/解密图像
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;
}
代码解密字节:
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;
}
,这是我在处理影像实现:
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);
我为我的英语不好对不起。在我的代码中,普通像素字节长度和加密字节长度不是相同的大小。当我读取加密图像的字节与普通字节的长度相同时。 我怀疑在保存过程中的错误,也许加密的字节在缓存图像保存时被修剪。如果我的假设是正确的,如何setDataElements的WritableRaster没有指定witdth和图像的高度?
你的问题不清楚。你担心,因为图像尺寸没有与栅格一起加密?你已经非常麻烦地加密*只*像素;如果要加密所有内容,只需加密整个文件(不使用图像API)。 – erickson
我很抱歉我的英文不好。在我的代码中,普通像素字节长度和加密字节长度不是相同的大小。当我读取加密图像的字节与普通字节的长度相同时。 我怀疑在保存过程中的错误,也许加密的字节在保存BufferedImage时被修剪。 –
@PutraArdiansyah哪个错误? – Kayaman