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!