title: Java cipher.doFinal() writing extra bytes
body: <p>I'm implementing encryption / decryption using Java Cipher and AES.  Everything is working well except that there's 5 extra bytes written on the call to doFinal().  So, I end up with a correctly decoded string with 5 extra bytes appended.</p>
  
  <p>I believe the reason is that the entire block of 16-bytes is being written.  I see 3 16-byte blocks written, including the last one.  The input encrypted file is 64-bytes.  The unencrypted text should be 43 bytes.</p>
  
  <p>The documentation for doFinal indicates that it can return the number of bytes written to the output buffer.  However, it's 0,16,16,16.  I've tried every form of doFinal and update and get no change in behavior.</p>
  
  <p>It kind of makes sense that it's writing out a full-block, since that's how most of these algorithms operate.  However, if it's not going to tell me the size of the output data, how am I supposed to prevent excess data?</p>
  
  <p>Should perhaps I be using another algorithm?  AES256 is a requirement, but I wonder if a different block type or padding type might allow it to write the correct number of bytes.</p>
  
  <p>Any guidance?</p>
  
  <p>Snipped for (some) brevity:</p>
  
  <pre><code>decryptCipher = Cipher.getInstance("AES");
  decryptCipher.init(Cipher.DECRYPT_MODE, aesKey);
  </code></pre>
  
  <p>Business part of the decryption routine.</p>
  
  <pre><code>    long bytesToRead = inputFile.length();
  
      while ((inLen = in.read(buffer)) &gt; 0) {
          int bytesOut = 0;
          byte[] cryptBytes = null;
          int outLen = cipher.getOutputSize(inLen);
          cryptBytes = new byte[outLen];
  
          if (bytesToRead &lt;= buffer.length) {
              try {
                  bytesOut = cipher.doFinal(buffer, 0, inLen, cryptBytes, 0);
              } catch (ShortBufferException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          } else
              try {
                  bytesOut = cipher.update(buffer, 0, inLen, cryptBytes, 0);
              } catch (ShortBufferException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
  
          out.write(cryptBytes, 0, bytesOut);
          bytesToRead -= inLen;
  
      }
      try {
          out.flush();
          in.close();
          out.close();
      } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
  </code></pre>