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.
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.