如何在java中加密图像

时间:2012-11-10 12:51:54

标签: encryption

需要建议,因为我仍然无法在java中成功加密/解密图像。 对于用户解密图像,用户必须单击图像并输入图像密码,类似于受密码保护的文本文件或pdf文件。

以下是java中加密Image的功能

public static void ImgEncrypt()throws Exception{

           // 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:/rose.jpg");
              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:/output.jpg");
             CipherOutputStream cos = new CipherOutputStream(
                    output, pbeCipher);
               //File outputFile = new File("image.png");
                 ImageIO.write(input,"JPG",cos);
              cos.close();    

    }
    }

1 个答案:

答案 0 :(得分:0)

打开文件时唯一可以解密的方法是它是一个自解密文件 - 操作系统可以运行的可执行文件,或者当关联的应用程序包含解密协议时。您不能只是单击自己加密的文件并期望它能够正常工作。