ECB加密的结果可能不同。它与CBC的结果相同

时间:2017-03-26 10:28:41

标签: java encryption encryption-symmetric cbc-mode ecb

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

}

1 个答案:

答案 0 :(得分:2)

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

如果你看到这些例子,肯定不会得到你期望的完美结果。你应该把这样的图片作为一个例子来证明这一点。