3

I basically use the code from here http://www.avajava.com/tutorials/lessons/how-do-i-encrypt-and-decrypt-files-using-des.html for an encryption app but I want to be able to chose the mode of operation so I added this:

private String key;
private static String algorithmMode;

    public DESCrypt(String password, String algorithmMode) {
        this.key = password;
        this.algorithmMode = "DES/" + algorithmMode + "/PKCS5Padding";
    }

the main looks like this:

public static void main(String[] args) {
        try {
            DESCrypt des = new DESCrypt("12345678", algorithmMode);

            // FileInputStream fis1 = new FileInputStream("d:\\_test.txt");
            // FileOutputStream fos1 = new FileOutputStream("d:\\_test.txt.des");
            // des.encrypt(fis1, fos1);

            FileInputStream fis = new FileInputStream("d:\\_test.txt.des");
            FileOutputStream fos = new FileOutputStream("d:\\_test.txt");
            des.decrypt(fis, fos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

As I was saying in the title it works fine with ECB but with other modes I can only encrypt.

Stoica Dan
  • 81
  • 1
  • 7

1 Answers1

7

You are missing an IV value for your decryption. You need to include this in your Cipher.init call:

... Cipher.init(Cipher.DECRYPT, someKey, new IvParameterSpec(eightByteValue));

If you omit it from your encryption code, a random IV value will be generated. You will need to store this (retrieved via Cipher.getIV()) to use in your decryption code.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
  • 2
    how would i transmit the IV? can i just bang it onto the byte array unencrypted? – rmalchow Jan 28 '16 at 11:19
  • @rmalchow: A normal practice to tranmit the IV is the prefix it to the ciphertext, then encode the entire byte[] with Base64 encoding. IV does not need to be encrypted while transmitting. See [aes128-cbc](https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#aes128-cbc) for an example of passing IV in plaintext. – leon Apr 07 '16 at 19:09