Can someone please help me? I'm getting an exception: Given final block not properly padded. I can't figure out what I'm doing wrong. Shouldn't Java automatically pad the data for me?

import java.security.*;
import java.io.*;
import javax.crypto.*;

public class AES
{
   static String fileName = "javaEncrypted.dat";
   static File inputFile = new File(fileName);
   static FileInputStream inputStream;
   static ObjectInputStream objectInput;
   static char[] buffer = new char[10000];
   static SecretKey inputKey;
   static byte length, encryptedMessage[], decryptedMessage[];

   public static void main(String[] args)
   {
	try
	{
	   inputStream = new FileInputStream(inputFile);
	   objectInput = new ObjectInputStream(inputStream);

	   // Read in objects from file
	   inputKey = SecretKey.class.cast(objectInput.readObject());
	   length = objectInput.readByte();
	   encryptedMessage = new byte[length];
	   decryptedMessage = new byte[length];
	   
	   objectInput.read(encryptedMessage, 0, length);
	   for(int x = 0; x < length; x++)
	   {
		System.out.print(encryptedMessage[x]);
	   }

	   // Print objects read in
	   System.out.println("\nInput key: " + inputKey.toString());
	   System.out.println("Key Length: " + length);
	   
	   // Create AES key generator
	   KeyGenerator keyGen = KeyGenerator.getInstance("AES");
	   keyGen.init(128);
	   
	   // Generate a secret key
	   SecretKey secretKey = keyGen.generateKey();
	   
	   // Create cipher
	   Cipher aesCipher = Cipher.getInstance("AES");
	   
	   // Set cipher to decrypt
	   aesCipher.init(Cipher.DECRYPT_MODE, secretKey);
	   System.out.println("TEST");

	   // Decrypt message
	   decryptedMessage = aesCipher.doFinal(encryptedMessage);

	   System.out.print("Decrypted message: ");
	   for(int x = 0; x < decryptedMessage.length; x++)
	   {
	      System.out.print(decryptedMessage[x]);
	   }
	   
	}
	catch(NoSuchAlgorithmException e)
	{
	   System.out.println(e.getMessage());
	}
	catch(NoSuchPaddingException e)
	{
	   System.out.println(e.getMessage());
	}
	catch(InvalidKeyException e)
	{
	   System.out.println(e.getMessage());
	}
	catch(FileNotFoundException e)
	{
	   System.out.println(e.getMessage());
	}
	catch(IOException e)
	{
	   System.out.println(e.getMessage());
	}
	catch(ClassNotFoundException e)
	{
	   System.out.println(e.getMessage());
	}
	catch(IllegalBlockSizeException e)
	{
	   System.out.println(e.getMessage());
	}
	catch(BadPaddingException e)
	{
	   System.out.println(e.getMessage());
	}
   }
}

Thanks in advance!

Also, if it helps, the output for this program is:
24-1012212520113-27105-10818-362076-6134277455-38-26819-861443-959789-7680
Input key: javax.crypto.spec.SecretKeySpec@fffe8163
Key Length: 32
TEST
Given final block not properly padded

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.