这是我的简单图像加密类,我在其中:
- 将图像从一个地方读入字节
- 加密这些字节
- 再次从这些加密字节创建图像
代码:
public class ImageEncrypt {
Cipher cipher;
public static byte[] convertImageToByteArray(String sourcePath) {
byte[] imageInByte = null;
try{
BufferedImage originalImage = ImageIO.read(new File(
sourcePath));
// convert BufferedImage to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos);
baos.flush();
imageInByte = baos.toByteArray();
baos.close();
}catch(Exception e){
e.printStackTrace();
}
return imageInByte;
}
public static void convertByteArrayToImage(byte[] b , String path) {
try{
InputStream in = new ByteArrayInputStream(b);
BufferedImage bImageFromConvert = ImageIO.read(in);
ImageIO.write(bImageFromConvert, "jpg", new File(
path));
}catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String args []){
final String strPassword = "password12345678";
SecretKeySpec initVector = new SecretKeySpec(strPassword.getBytes(), "AES");
AlgorithmParameterSpec paramSpec = new IvParameterSpec(strPassword.getBytes());
try{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, initVector, paramSpec);
byte[] ecrypted = cipher.doFinal(convertImageToByteArray("C:/Users/user/Desktop/a.jpg"));
convertByteArrayToImage(ecrypted,"C:/Users/user/user/enc.jpg");
System.out.println("converted to encrypted file .... ");
}catch(Exception e){
e.printStackTrace();
}
}
现在,当我尝试从加密字节制作图像时,我在第三步遇到了问题。它抛出下面给出的异常:
java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
at javax.imageio.ImageIO.getWriter(ImageIO.java:1591)
at javax.imageio.ImageIO.write(ImageIO.java:1520)
at ImageEncrypt.convertByteArrayToImage(ImageEncrypt.java:55)
at ImageEncrypt.main(ImageEncrypt.java:83)
我不知道我哪里出错了?我正在做同样的事情来将文件(文档,pdf等)转换为加密并且它工作正常(当然在这种情况下我使用不同的流类进行字节转换)但我无法理解为什么它在这里搞砸了?