title: AES-256 CBC encrypt in php and decrypt in Java or vice-versa
body: <h2>JAVA</h2>
  
  <pre><code>import javax.crypto.Cipher;
  import javax.crypto.spec.IvParameterSpec;
  import javax.crypto.spec.SecretKeySpec;
  import org.apache.commons.codec.binary.Base64;
  
  class AES256JavaPhp{
          public static void main(String[] args) throws Exception {
                  Base64 base64 = new Base64();
                  Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
                  SecretKeySpec key = new
                            SecretKeySpec("PasswordPassword".getBytes("UTF-8"),"AES");
                  IvParameterSpec iv = new IvParameterSpec
                        ("dynamic@dynamic@".getBytes("UTF-8"),0,ciper.getBlockSize());
              //Encrypt
                  ciper.init(Cipher.ENCRYPT_MODE, key,iv);
                  byte[] encryptedCiperBytes = base64.encode
                                                ((ciper.doFinal("Hello".getBytes())));
                  System.out.println("Ciper : "+new String(encryptedCiperBytes));
              //Decrypt
                  ciper.init(Cipher.DECRYPT_MODE, key,iv);    
                  byte[] text = ciper.doFinal(base64.decode(encryptedCiperBytes));
                  System.out.println("Decrypt text : "+new String(text));
            }
      }
  </code></pre>
  
  <p>Java output:</p>
  
  <pre><code>Ciper : KpgzpzCRU7mTKZePpPlEvA==
  Decrypt text : Hello
  </code></pre>
  
  <h2>PHP</h2>
  
  <pre><code>&lt;?php&gt;    
          $cipherText = encrypt("Hello", 'aes-256-cbc');
          exit();
  
          function encrypt($data, $algo)
          {
              $key = 'PasswordPassword';
              //$iv = random_bytes(openssl_cipher_iv_length($algo));
              $iv = 'dynamic@dynamic@';
              $cipherText = openssl_encrypt(
                      $data,
                      $algo,
                      $key,
                      OPENSSL_RAW_DATA,
                      $iv
                  );
          $cipherText = base64_encode($cipherText);
          printData("Ciper Text : $cipherText");
  
          $cipherText = base64_decode($cipherText);
          $plaintext = openssl_decrypt(
                      $cipherText,
                      $algo,
                      $key,
                      OPENSSL_RAW_DATA,
                      $iv
                  );
          printData("Plain Text after decryption : $plaintext");
          }
  
          function printData($obj)
          {
              print_r($obj);
          }
  ?&gt;
  </code></pre>
  
  <p>PHP output:</p>
  
  <pre><code>Ciper Text : ef/ENVlBn9QBFlkvoN7P2Q==
  Plain Text after decryption : Hello
  </code></pre>
  
  <p>The resulting ciphers are different, even though they are using the same key and IV. How is this possible?</p>