user3809036
user3809036

Reputation: 11

Properly decrypting a file using AES/CBC/PKCS5Padding - BadPaddingException

When I try to decrypt the following file, I get this BadPaddingException at the following line. I believe the file is encrypted properly.

javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:810)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:675)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:313)
    at javax.crypto.Cipher.doFinal(Cipher.java:1970)
    **at MyProgram.decryptFile(MyProgram.java:1437)**
    at MyProgram.decrypt(MyProgram.java:865)
    at MyProgram.access$900(MyProgram.java:68)
    at MyProgram$1.messagesAdded(MyProgram.java:353)
    at javax.mail.event.MessageCountEvent.dispatch(MessageCountEvent.java:150)
    at javax.mail.EventQueue.run(EventQueue.java:135)
    at java.lang.Thread.run(Thread.java:722)

This is the decryption code, I can send code on the encrypted part as well:

private static void decryptFile(String file, String password, byte[] Salt, byte[] IV, String attachmentunecryptedhash, String attachmentoriginalsizeString, String attachmentcreated)
{
        long attachmentSize = 0;
        String attachmentCreated = null;
        String attachmentModified = null;
        String attachmentHash = null;
        byte[] buffers = new byte[16];
        byte[] endOfFile = new byte[16];
        int counterForFile = 0;
        int attachmentoriginalsize = 0;
        int noBytes = 0;

        try
        {
            if(Paths.get(file.trim()).toFile().exists() == true) //If the File Exists
            {
                //Creates Secret Key For Decryption -- Passes Password, Salt, Iterations, and Key Length
                PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), Salt, 65536, 256);
                SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
                SecretKey secretKey = factory.generateSecret(keySpec);
                SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

                //Initalizes Cipher For Decrypt Mode -- Passes Password and Salt
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));

                //Prepares To Write New Buffer Containing Decrypted Information to Output File
                String unencryptedFile = file.trim().replaceAll(".aes", "");
                FileInputStream fileInputStream = new FileInputStream(file.trim());
                FileOutputStream fileOutputStream = new FileOutputStream(unencryptedFile);
                attachmentoriginalsize = Integer.parseInt(attachmentoriginalsizeString);



                //Writes Encrypted File to Disk Using Secure Cipher Output Stream
                while((noBytes = fileInputStream.read(buffers)) != -1)
                {

                    //Writes 1 encrypted byte at a time
                    fileOutputStream.write(cipher.update(buffers,0,noBytes));
                    //counterForFile += 16;
                }

                buffers = cipher.doFinal();  //Line 1437 Where the Error Exists

                fileOutputStream.write(buffers);
                fileOutputStream.flush();


                //Close Files, Cleanup
                fileInputStream.close();
                fileOutputStream.close();

                System.exit(1);

}

Upvotes: 1

Views: 1090

Answers (1)

rossum
rossum

Reputation: 15685

There are many things that can cause a "Bad Padding" error. Basically anything that causes the end of the last block not to match the expected padding will throw the error. Possible causes include: incorrect padding setting, incorrect key, corrupted cyphertext and others.

To try and diagnose the problem, set the decryption side to NoPadding. This will accept anything, and allow you to examine the output:

  • complete garbage: you probably have an error in the key or different mode settings.

  • first block garbage: you may have a key error or an IV error.

  • last block garbage: likely a corrupt end to the cyphertext file.

  • a correct decryption with some strange bytes at the end: the strange bytes are the padding.

If it really is just the padding, then set the decryption function to expect that sort of padding. Otherwise check that the key/IV/cyphertext is byte-for-byte the same for both encryption and decryption.

It is vital that you set a padding mode after diagnosis. NoPadding is insecure.

Upvotes: 1

Related Questions