JAVA:如何加密和查看图像

JAVA:如何加密和查看图像,java,encryption,aes,imaging,cbc-mode,Java,Encryption,Aes,Imaging,Cbc Mode,我必须用Java加密图像。我正确地加密了图像,但我不知道如何可视化它,因为当我试图打开文件时,系统会告诉我图像太长或是一个损坏的文件。在没有元数据的情况下,如何处理pic主体 谢谢 // Scanner to read the user's password. The Java cryptography // architecture points out that strong passwords in strings is a // bad idea, but we'

我必须用Java加密图像。我正确地加密了图像,但我不知道如何可视化它,因为当我试图打开文件时,系统会告诉我图像太长或是一个损坏的文件。在没有元数据的情况下,如何处理pic主体

谢谢

    // 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();

    }
}

您正在加密整个输出文件。当然,加密的表单不是可重新识别的图像文件类型;如果是加密的话,那就没什么意义了

您似乎希望对图像数据进行加密,但将其作为有效图像写入;然后,图像将显示随机像素。原则上,这并不复杂,只需对已读取图像中的像素进行加密,然后正常写入该图像即可

在实践中,这并不是那么简单,因为密码设计用于处理流,而图像有一个适合图形处理的API;为了使事情更加复杂,内部使用了不同的表示来表示不同类型的图像


因此,您需要编写一些粘合代码来在两者之间进行翻译;从图像中获取像素(例如使用getRGB(x,y)方法),将像素数据分解为字节;把它输入密码;并将加密数据转换回像素(例如,使用setRGB(x,y,rgb))。

您直接将输出位写入新的
.png
文件。也许你需要写正确的元数据,然后写加密的数据
.png
有一个可以查看的标准。对原始图像来说,这样做可能更容易,只需以字节为单位指定每个像素的颜色代码,例如。也就是说,使用DES和MD5,您可以快速强制密码解密标题:P