title: Java: Bad padding error when decrypting from encrypted file
body: <p>I am building a file encryption utility, here's my encryption code:</p>
  
  <pre><code>    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
      SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
      cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
      for(int i = 0; i &lt; input.size(); i++){
          plainText = input.get(i);
          byte[] b = cipher.doFinal(plainText.getBytes("UTF-8"));
          String outString = new String(b);
          //to be written to file
  </code></pre>
  
  <p>The strings to encrypt are read in from an array (the utility does other data processing) and then encrypted, and output in an array of strings to write to a file when ready.</p>
  
  <p>When decrypting, I get an error that my padding is wrong. I have been researching and gather that this is down to .getBytes() not returning the byte array exactly as it was. I am reading line by line from file that has been encrypted using my previous code. How can I ensure that my decryption function receives the correct byte array?</p>
  
  <p>Here is the code:</p>
  
  <pre><code>public void decode(File f) throws Exception{
       BufferedWriter out = new BufferedWriter(new FileWriter("Decrypted Archive "+f.getName()+".txt"));
       BufferedReader br = new BufferedReader(new FileReader(f));
       String line;
       while((line = br.readLine())!=null){
           byte[] b = line.getBytes("UTF-8"); 
           line = Decoder.decrypt(b);
           out.write(line+newline);
       }
       br.close();
       out.close();
  </code></pre>
  
  <p>And the decrypt function:</p>
  
  <pre><code>public static String decrypt(byte[] cipherText) throws Exception{
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
      SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
      cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
      return new String(cipher.doFinal(cipherText),"UTF-8");
    }
  </code></pre>
  
  <p>Encryption keys etc are all the same.</p>