import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Security; import javax.imageio.ImageIO; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Hex; public class TwelveMonkeysImageTest { public static void main(String[] args) throws Exception { // // Bouncy Castle Security Provider // Security.addProvider(new BouncyCastleProvider()); // // TwelveMonkeys Java ImageIO extensions // // (automatically detected just must be in class path). // // Check args. // if (args.length < 1) { System.err.println("Error: Loading needs 1 argument - source path"); System.exit(1); } load(args[0]); } public static void load(String sourcePath) throws Exception { BufferedImage image; BufferedImage loadedImage = ImageIO.read(new File(sourcePath)); if (loadedImage == null) { System.out.println("Skipping non-image file."); throw new Exception("non-image file"); } int width = loadedImage.getWidth(); int height = loadedImage.getHeight(); loadedImage = ImageIO.read(new File(sourcePath)); System.out.format("Loaded Image SHA-256: %s\n", sha256Image(loadedImage, width, height)); image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); image.createGraphics().drawImage(loadedImage, 0, 0, Color.WHITE, null); System.out.format("SHA-256: %s\n", sha256Image(image, width, height)); ImageIO.write(image, "tiff", new File("1.tiff")); loadedImage = ImageIO.read(new File("1.tiff")); System.out.format("Loaded Image SHA-256: %s\n", sha256Image(loadedImage, width, height)); image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); image.createGraphics().drawImage(loadedImage, 0, 0, Color.WHITE, null); System.out.format("SHA-256: %s\n", sha256Image(image, width, height)); ImageIO.write(image, "tiff", new File("2.tiff")); loadedImage = ImageIO.read(new File("2.tiff")); System.out.format("Loaded Image SHA-256: %s\n", sha256Image(loadedImage, width, height)); image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); image.createGraphics().drawImage(loadedImage, 0, 0, Color.WHITE, null); System.out.format("SHA-256: %s\n", sha256Image(image, width, height)); ImageIO.write(image, "tiff", new File("3.tiff")); return; } public static String sha256Image(BufferedImage img, int width, int height) throws NoSuchAlgorithmException, NoSuchProviderException { // // SHA256 digest of the image data. // ByteBuffer byteBuffer = ByteBuffer.allocate(4 * width * height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { byteBuffer.putInt(img.getRGB(x, y)); } } // hash.reset(); MessageDigest hash = MessageDigest.getInstance("SHA-256", "BC"); hash.update(byteBuffer.array()); return Hex.toHexString(hash.digest()); } }