0

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!

  • 1
    You aren't actually reading anything into `inputBytes` before calling `doFinal` - so you are trying to decrypt garbage (all zeros) instead of the contents of the file. (You have the same error on the encrypt side.) For simplicity, assuming reasonably sized files for now, check out: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#readAllBytes-java.nio.file.Path- – Richard Heap Apr 11 '22 at 17:49
  • Your "encrypt" method encrypts an `inputBytes` array full of zeros and throws away the result. It the copies the (unencrypted) input stream into the output stream. – Thomas Kläger Apr 11 '22 at 18:06
  • Does this answer your question? [Encrypting a large file with AES using JAVA](https://stackoverflow.com/questions/34447037/encrypting-a-large-file-with-aes-using-java) – Thomas Kläger Apr 11 '22 at 18:10
  • The possible duplicate has an answer to the encryption problem. Decryption works similarly. – Thomas Kläger Apr 11 '22 at 18:10
  • One thing that is often overlooked is the new IO, where you can map a file into memory. Note that "coincidentally" you can also use `ByteArray` buffers in the implementations of `Cipher`. – Maarten Bodewes Apr 11 '22 at 20:33

0 Answers0