1
votes

I'm trying to use JDK 1.7 JCE (Windows 7 x64) to perform Single DES encryption with CBC on a small block. Each time I run the program below I get different results. The key is the same, the data is the same, what could be wrong?

public class CBCTest {
    public static void main(String[] args) throws Exception {
        Cipher cc = Cipher.getInstance("DES/CBC/NoPadding");
        Key k = new SecretKeySpec(new byte[] {1,1,1,1,1,1,1,1}, "DES");
        cc.init(Cipher.ENCRYPT_MODE, k);
        byte[] data = new byte[]{1,2,3,4,5,6,7,8};
        cc.doFinal(data);
        System.out.println("Encrypted: " + Arrays.toString(cc.doFinal(data)));
    }
}

Edit: Changing the Cipher mode to ECB "DES/CBC/NoPadding" works without a problem.

1

1 Answers

1
votes

For CBC mode there is a further input namely the IV (initialization vector). Make sure to use the same IV for each run then you will get identical output.

See the documentation for the details.

Btw. it is not a bad idea to use a random IV, this makes sure that there is a different ciphertext each time if the same message is sent several times. This is especially important if the number of possible messages is low. It makes it much harder for an eavesdropper to guess the meaning of a certain bit pattern.