I am having issues with my code. The instructions are as followed: This project has the following requirements:
- Ask the user for a string of characters.
- Encrypts the string of characters using a password entered by the user. The process of encryption is carried out using the DES cipher implemented in Java.
- Print in the console the encrypted byte array.
- Decrypts the message back to the original byte array and prints it in the console.
I am having issues with Step 2 and Step 4. May you please advise me on what to do. I keep getting the error : Exception in thread "main" j
avax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:991)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DESCipher.java:314)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at Main.main(Main.java:50)
May you please advise me on what to do.
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException {
Scanner scan = new Scanner(System.in);
System.out.println("Please Input A String Of Characters:");
String myString = scan.nextLine();
System.out.println("Please Input a Password:");
String passw = scan.nextLine();
SecretKeyFactory MyKeyFactory = SecretKeyFactory.getInstance("DES");
byte[] mybytes = myString.getBytes("UTF8");
DESKeySpec myMaterial = new DESKeySpec(mybytes);
SecretKey myDESkey = MyKeyFactory.generateSecret(myMaterial);
Cipher desCipher = Cipher.getInstance("DES");
desCipher.init(Cipher.ENCRYPT_MODE, myDESkey);
byte[] myEncryptedBytes = desCipher.doFinal(mybytes);
System.out.println(Arrays.toString(myEncryptedBytes));
desCipher.init(Cipher.DECRYPT_MODE, myDESkey);
byte[] myDecryptedBytes = desCipher.doFinal(mybytes);
System.out.println(Arrays.toString(myDecryptedBytes));
}
}