0

我必须使用 Java 加密图像。我正确加密了图像,但我不知道如何将其可视化,因为当我尝试打开文件时,系统告诉我图像太长或文件损坏。在没有元数据的情况下,如何使用图片正文?

谢谢!!

    // Scanner to read the user's password. The Java cryptography
    // architecture points out that strong passwords in strings is a
    // bad idea, but we'll let it go for this assignment.
    Scanner scanner = new Scanner(System.in);
    // Arbitrary salt data, used to make guessing attacks against the
    // password more difficult to pull off.
    byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
            (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 };

    {
        File inputFile = new File("C:/Users/Julio/Documents/charmander.png");
        BufferedImage input = ImageIO.read(inputFile);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeyFactory keyFac = SecretKeyFactory
                .getInstance("PBEWithMD5AndDES");
        // Get a password from the user.
        System.out.print("Password: ");
        System.out.flush();
        PBEKeySpec pbeKeySpec = new PBEKeySpec(scanner.nextLine()
                .toCharArray());
        // Set up other parameters to be used by the password-based
        // encryption.
        PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
        // Make a PBE Cyhper object and initialize it to encrypt using
        // the given password.
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
        FileOutputStream output = new FileOutputStream(
                "C:/Users/Julio/Documents/imgen.png");
        CipherOutputStream cos = new CipherOutputStream(output, pbeCipher);
        // File outputFile = new File("image.png");
        ImageIO.write(input, "PNG", cos);
        cos.close();

    }
}
4

1 回答 1

1

您正在加密整个输出文件。当然,加密形式不是可识别的图像文件类型;如果它是加密将有点毫无意义。

您似乎想要的是加密图像数据,但将其写为有效图像;然后图像似乎只显示随机像素。原则上这并不复杂,只需对您读取的图像中的像素应用加密,然后正常写入该图像。

实际上它并不简单,因为 cyphers 被设计用于处理流,而图像有一个适用于图形处理的 API;为了让事情变得更复杂,内部使用了不同的表示来表示不同类型的图像。

所以你需要写一些胶水代码在两者之间进行翻译;从图像中获取像素(例如使用 getRGB(x, y) 方法),将像素数据分解为字节;将其输入密码;并将加密数据转换回像素(例如使用 setRGB(x, y, rgb))。

于 2014-10-29T18:00:14.583 回答