0

Have a project in my coding class and I can't figure out this one. The encryption of the file goes just fine it encrypts just fine but whenever I get to the decoding I get this error: Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. I don't know why this is happening so that is why I'm here. Here's the code:

package Test;
 import java.io.*;
 import java.security.*;
 import javax.crypto.*;
 import javax.crypto.spec.*;
 import java.util.*;

 public class FileDecryptor
 {
    private static String filename;
    private static String password;
    private static FileInputStream inFile;
    private static FileOutputStream outFile;

    public static void main(String[] args) throws Exception
    {

       // File to decrypt.

       filename = "Test.txt.des";

       String password = "super_secret_password";

       inFile = new FileInputStream(filename);
       outFile = new FileOutputStream(filename + ".dcr");

       PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
       SecretKeyFactory keyFactory =
           SecretKeyFactory.getInstance("PBEWithMD5AndDES");
       SecretKey passwordKey = keyFactory.generateSecret(keySpec);

       byte[] salt = new byte[8];
       inFile.read(salt);
       int iterations = 100;

       PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);


       Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
       cipher.init(Cipher.DECRYPT_MODE, passwordKey, parameterSpec);

       outFile.write(salt);


       byte[] input = new byte[64];
       int bytesRead;
       while ((bytesRead = inFile.read(input)) != -1)
       {
          byte[] output = cipher.update(input, 0, bytesRead);
          if (output != null)
             outFile.write(output);
       }
       byte[] output = cipher.doFinal();
       if (output != null)
          outFile.write(output);

       inFile.close();
       outFile.flush();
       outFile.close();
   }
}
  • MD5 and DES are both extremely insecure. – SLaks Dec 04 '14 at 22:10
  • http://stackoverflow.com/questions/4580982/javax-crypto-badpaddingexception maybe this helps – joh.scheuer Dec 04 '14 at 22:26
  • 2
    You may be having a problem in you encryption class. Please post an [MCVE](http://stackoverflow.com/help/mcve). You can edit your question. – Artjom B. Dec 04 '14 at 23:35
  • See my answer here: http://stackoverflow.com/questions/19195657/when-decrypting-image-gives-javax-crypto-badpaddingexception-pad-block-corrupt/19198139#19198139 That might help. – rossum Dec 06 '14 at 11:38

0 Answers0