title: Encryption from PHP to Java (Android): How to Fix Error "Wrong Final Block Length"?
body: <p>Have tried several different methods found on Google and SOF, but I just can't seem to get this to work. I am trying to encrypt a string in PHP and decrypt it in Java (Android activity). In PHP to encrypt the string, I'm using AES-256-CBC with a sha256 hash (which encrypts/decrypts successfully in PHP). The issue is that no matter what I try, I can't get the unencrypted string in Java. My latest attempt ended with a console error of "Cipher functions:OPENSSL_internal:WRONG_FINAL_BLOCK_Length".</p>
  
  <p>I suspect my issue is with Base64 encoding, but all of my attempts so far have failed spectacularly. Or perhaps I'm using the wrong Cipher on the Java end. I've read about some people needing to convert to hex, though I didn't understand why.</p>
  
  <p>Please note, the iv and key are not really the same, just using the same here for example's sake.</p>
  
  <p>My PHP code:</p>
  
  <pre><code>$secret_key = "1111111111111111";
  $secret_iv = "1111111111111111";
  
  $encrypt_method = "AES-256-CBC"; 
  $key = hash( 'sha256', $secret_key );
  $iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
  $output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
  </code></pre>
  
  <p>My Java code:</p>
  
  <pre><code>    String given_iv = "1111111111111111";
      String key = "1111111111111111";
  
      IvParameterSpec iv = new IvParameterSpec(given_iv.getBytes());
      SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
  
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
      cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
  
      byte[] decodedEncryptedData = Base64.decode(data.getBytes(),Base64.NO_WRAP);
  
      byte[] original = cipher.doFinal(decodedEncryptedData);
      Log.i(TAG, "Result: " + new String(original));
      return new String(original);
  </code></pre>
  
  <p>Can someone please tell me where I went wrong. Thanks.</p>
  
  <p>Update 1:
  As pointed out by @Peter and @Topaco, I was Base64 encoding twice on the PHP side, this was removed as well as using the key/IV directly on the Java side. Unfortunately, the error persists.</p>
  
  <p>PHP code now:</p>
  
  <pre><code>    $secret_key = "1111111111111111";
      $secret_iv = "1111111111111111";
  
      $encrypt_method = "AES-256-CBC"; 
      $output = openssl_encrypt( $string, $encrypt_method, $secret_key, 0, $secret_iv );
  </code></pre>
  
  <p>Java code still remains the same. However I was messing around with Cipher.getInstance("AES/CBC/PKCS5PADDING") and changed it to "AES/CBC/NOPADDING", it changed the error, I now get an output of garbled text, but still no real luck on decrypting fully.</p>