I have two classes named encryption.java and decryption.java. I want encrypt a text file using the encrypt.java class and decrypt from decrypt.java class. I can encrypt the text file successfully, but not able to decrypt it in same way. Can anyone tell me why not?
This is encrypt.java:
public class Encrypt{
public static void main(String[] args) throws Exception {
String FileName = "D:/ashok/normal.txt";
String FileName1 = "D:/ashok/encrypted.txt";
KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
KeyGen.init(128);
SecretKey SecKey = KeyGen.generateKey();
Cipher AesCipher = Cipher.getInstance("AES");
byte[] cipherText = Files.readAllBytes(Paths.get(FileName));
AesCipher.init(Cipher.ENCRYPT_MODE, SecKey);
byte[] byteCipherText = AesCipher.doFinal(cipherText);
Files.write(Paths.get(FileName1), byteCipherText);
}
This is my decrypt.java class:
class decrypt{
public static void main(String[] args) {
try {
String FileName1 = "D:/ashok/encrypted.txt";
String FileName2 = "D:/ashok/decrypted.txt";
KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
KeyGen.init(128);
SecretKey SecKey = KeyGen.generateKey();
Cipher AesCipher = Cipher.getInstance("AES");
byte[] cipherrText = Files.readAllBytes(Paths.get(FileName1));
AesCipher.init(Cipher.DECRYPT_MODE, SecKey);
byte[] bytePlainText = AesCipher.doFinal(cipherrText);
Files.write(Paths.get(FileName2), bytePlainText); }}
and getting error when decrypt class runs, like this
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:313)
at javax.crypto.Cipher.doFinal(Cipher.java:2086)
at decryption.main(decryption.java:79)