Hello. I submitted this post a little while ago where I had problems with decrypting what I encrypted. Now my problem is that when I encrypt something and then decrypt it, the decryption works with txt files, but when I try to decrypt microsoft documents, then they will not open. I did a couple of tests, and it seems like any more advanced file will get corrupted (pdf, docx, ppt, etc.) Here is my new code for the encryption
package sec;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.*;
public class Cryption {
private Cipher c;
private SecretKey k;
private byte[] iv = {0,0,0,0,0,0,0,0};
public Cryption(){
try {
c = Cipher.getInstance("DES/CBC/PKCS5Padding");
KeyGenerator kg = KeyGenerator.getInstance("DES");
k = kg.generateKey();
System.out.println("k = " + k);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String encrypt(String dec) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException{
KeyGenerator kg = KeyGenerator.getInstance("DES");
k = kg.generateKey();
IvParameterSpec ivspec = new IvParameterSpec (iv);
c.init(Cipher.ENCRYPT_MODE, k, ivspec);
String enc = new String(c.doFinal(dec.getBytes()));
return enc;
}
public String decrypt(String enc) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException{
IvParameterSpec ivspec = new IvParameterSpec (iv);
//System.out.println("k = " + k);
c.init(Cipher.DECRYPT_MODE, k, ivspec);
String dec = new String(c.doFinal(enc.getBytes()));
return dec;
}
public String saveKey(){
byte[] enc = k.getEncoded();
String save = new BigInteger(1, enc).toString(16);
return save;
}
public void loadKey(String s){
byte[] enc = new BigInteger(s, 16).toByteArray();
k = new SecretKeySpec(enc, "DES");
}
}
How can I fix this problem?
Thanks for the help.