1
public class Symmetric1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception{
        // TODO code application logic here
        KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(new SecureRandom());
    SecretKey secretKey = kg.generateKey();

    FileInputStream inFile = new FileInputStream("C:/Users/Administrator/Desktop/original.bmp");

    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); 
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    FileOutputStream outFile = new FileOutputStream("C:/Users/Administrator/Desktop/ECB_original.bmp");

    byte[] input = new byte[64];
    int bytesRead;
    while((bytesRead = inFile.read(input)) != -1){
        byte[] output = cipher.update(input,0,bytesRead);
        if(output != null)
            outFile.write(output);
    }

    byte[] output = cipher.doFinal();
    if(output != null)
        outFile.write(output);

    inFile.close();
    outFile.flush();
    outFile.close();
    }
}

我了解到 ecb 加密使图片有点模糊......但是我的代码使原始图片像 CBC 加密一样加密。怎么了?

这也是 cbc 加密代码。

public class Symmetric2 {

    public static void main(String[] args) throws Exception{
        // TODO Auto-generated method stub

        FileInputStream inFile = new FileInputStream("C:/Users/Administrator/Desktop/original.bmp");
        FileOutputStream outFile = new FileOutputStream("C:/Users/Administrator/Desktop/CBC_original.bmp");

        KeyGenerator kg = KeyGenerator.getInstance("DES");
        kg.init(new SecureRandom());

        SecretKey sk = kg.generateKey();

        Cipher cp = Cipher.getInstance("DES/CBC/PKCS5Padding");

        byte[] ivBytes = new byte[]{
                0x00, 0x01,0x02, 0x03, 0x00, 0x00, 0x00, 0x01       };
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        cp.init(Cipher.ENCRYPT_MODE, sk, ivSpec); //CBC방식이므로 인자가 3개이다.

        byte[] input = new byte[64]; //getBytes() 
        int bytesRead;
        while((bytesRead = inFile.read(input)) != -1){
            byte[] output = cp.update(input,0,bytesRead);
            if(output != null)
                outFile.write(output);
        }
        byte[] output = cp.doFinal();
        if(output != null)
            outFile.write(output);

        inFile.close();
        outFile.flush();
        outFile.close();
    }

}
4

1 回答 1

2

众所周知的企鹅图片有点脏。它只加密位图本身,而 BMP 文件还包含元数据。此外,它依赖于数据的正确对齐。

如果您看到这些示例,肯定不会得到您期望的完美结果。您应该以这样的图片为例来证明这一点。

于 2017-03-26T13:25:26.607 回答