I am attempting to encrypt and string and then decrypt it. I have the encryption part working, but when I try to decrypt it gives me an InvalidKeyException and says that it is missing parameters.
Here is the code
import javax.crypto.*;
import java.security.*;
public class Cryption {
private Cipher c;
private Key k;
public Cryption(){
try {
c = Cipher.getInstance("DES/CBC/PKCS5Padding");
KeyGenerator kg = KeyGenerator.getInstance("DES");
k = kg.generateKey();
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String encrypt(String dec){
try {
c.init(Cipher.ENCRYPT_MODE, k);
String enc = new String(c.doFinal(dec.getBytes()));
return enc;
} catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String decrypt(String enc){
try {
c.init(Cipher.DECRYPT_MODE, k);
String dec = new String(c.doFinal(enc.getBytes()));
return dec;
} catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
and here is the output that I get when I run the program passing in the string Hello World
Hello World
oØÁÖG _|bÁW3°
java.security.InvalidKeyException: Parameters missing
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:388)
at com.sun.crypto.provider.DESCipher.engineInit(DESCipher.java:186)
at javax.crypto.Cipher.init(Cipher.java:1210)
at javax.crypto.Cipher.init(Cipher.java:1153)
at Cryption.decrypt(Cryption.java:35)
at Main.main(Main.java:12)
null
The main method mentioned is just a test class