Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Problem when decrypt file use AES-128bits Java

I have a method doCrypt to encrypt and decrypt a file. Encrypting is good but when I try to decrypt, it has some problem. Here is my code:

private static void doCrypto(int cipherModel, String password, File inputFile, File outputFile) {
    try {

        KeyGenerator keyGenerator = new KeyGenerator();
        byte[] key = keyGenerator.generateKey(password, 16);
        System.out.println("Key :::::::" + Arrays.toString(key));
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(cipherModel, keySpec,ivSpec);
        System.out.println("cipher init done");


        FileInputStream inputStream = new FileInputStream(inputFile);
        FileOutputStream outputStream = new FileOutputStream(outputFile);
        byte[] inputBytes = new byte[16];
        byte[] outputBytes;
        int count;
        while ((count = inputStream.read(inputBytes))>0){
            outputBytes = cipher.doFinal(inputBytes);
            outputStream.write(outputBytes);
        }
        inputStream.close();
        outputStream.close();


    } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | IOException ex) {
        System.out.println(ex.getMessage());
    } catch (InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
}
  • When i use byte[] inputBytes = new byte[5]; or 6,... Problem is : javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
  • When i use byte[] inputBytes = new byte[16]; bigger Problem is : javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

How can I solve the problem?

Comments