title: Cipher doFinal pad block corrupted while decrypting file with AES
body: <p>I am creating a program that lets users upload and download encrypted files and decrypt them if they have the correct permissions to do so. Encrypting and uploading is fine, and so is downloading, but when I try to decrypt I get the "pad block corrupted" error.</p>
  
  <p>What I am trying to do is take the encrypted file and then make a copy that is unencrypted</p>
  
  <p>I shortened what I could so please don't comment that it looks incomplete.</p>
  
  <p>KeyGen:</p>
  
  <pre><code>public static SecretKey genGroupSecretKey() {
      try {
          KeyGenerator keyGen = KeyGenerator.getInstance("AES", "BC");
          keyGen.init(128);
          return keyGen.generateKey();
      } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
          System.err.println("Error: " + e.getMessage());
          e.printStackTrace(System.err);
      }
      return null;
  }
  </code></pre>
  
  <p>Encrypt:</p>
  
  <pre><code>try (FileInputStream fis = new FileInputStream(sourceFile)) {
      response = Utils.decryptEnv((byte[]) tempResponse.getObjContents().get(0), fsSecretKey, ivSpec);
  
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
  
      do {
          byte[] buf = new byte[4096];
  
          int n = fis.read(buf); // can throw an IOException
          else if (n &lt; 0) {
              System.out.println("Read error");
              fis.close();
              return false;
          }
  
          byte[] cipherBuf = cipher.doFinal(buf);
  
          // send through socket blah blah blah
  
      } while (fis.available() &gt; 0);
  </code></pre>
  
  <p>Decrypt:</p>
  
  <pre><code>   ...     
  
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
     cipher.init(Cipher.DECRYPT_MODE, secKey, ivSpec);
  
      File file = new File("D_" + filename); // D_ for decrypted
      FileOutputStream fos = null;
      if (!file.exists()) {
          file.createNewFile();
          fos = new FileOutputStream(file);
      }
  
      try (FileInputStream fis = new FileInputStream(filename)) {
          do {
              byte[] buf = new byte[4096];
              int n = fis.read(buf);
              if (n &lt; 0) {
                  System.out.println("Read error");
                  fis.close();
                  return false;
              }
  
              byte[] cipherBuf = cipher.doFinal(buf);  // ERROR HERE
              System.out.println("IS THIS WORKING WTF: " + new String(cipherBuf));
              fos.write(cipherBuf, 0, n);
  
          } while (fis.available() &gt; 0);
          fis.close();
          fos.close();
          return true;
  </code></pre>