I'm trying to encrypt a file using AES and Java Crypto Library. But this is the error Which happens while I'm decrypting the file: "Error while decrypting: javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption."
This is my code so far:
public static void encrypt(File input, String key, File output) {
try
{
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(key.toCharArray(), key.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
FileInputStream inputStream = new FileInputStream(input);
byte[] inputBytes = new byte[(int) input.length()];
int count;
byte[] outputBytes = cipher.doFinal(inputBytes);
FileOutputStream outputStream = new FileOutputStream(output);
while ((count = inputStream.read(inputBytes, 0, inputBytes.length)) > 0)
{
outputStream.write(inputBytes, 0, count);
}
inputStream.close();
outputStream.close();
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
}
public static void decrypt(File input, String key, File output)
{
try
{
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(key.toCharArray(), key.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
FileInputStream inputStream = new FileInputStream(input);
byte[] inputBytes = new byte[(int) input.length()];
int count;
byte[] outputBytes = cipher.doFinal(inputBytes);
FileOutputStream outputStream = new FileOutputStream(output);
while ((count = inputStream.read(inputBytes, 0, inputBytes.length)) > 0)
{
outputStream.write(inputBytes, 0, count);
}
inputStream.close();
outputStream.close();
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
}
What could be the problem? Thanks in advance!