AES Interop Between PHP and Java (Part 4)

… “After started something, you have to finish it” my dad used to tell me…

The Problem: Part 3 was to encrypt a binary file (PDF) in PHP and decrypt it over in Java. It is of course natural to complete it to do it the other way around.

This is actually just flipping some code, real simple, just that I am so busy recently that I have not made time for it.

The Solution:

  1. Encrypt a message in Java:
    001	import java.io.*;
    002	import javax.crypto.*;
    003	import javax.crypto.spec.*;
    004
    005	public class encrypt {
    006	  public static void main(String args[]) throws Exception {
    007	    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    008	    SecretKeySpec keySpec =
    009	      new SecretKeySpec("01234567890abcde".getBytes(), "AES");
    010	    IvParameterSpec ivSpec =
    011	      new IvParameterSpec("fedcba9876543210".getBytes());
    012	    cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
    013	    FileInputStream fis   =
    014	      new FileInputStream(new File("plain.pdf"));
    015	    CipherInputStream cis = new CipherInputStream(fis, cipher);
    016	    FileOutputStream fos  =
    017	      new FileOutputStream(new File("encrypted.pdf"));
    018
    019	    byte[] b = new byte[8];
    020	    int i;
    021
    022	    while ((i = cis.read(b)) != -1) {
    023	      fos.write(b, 0, i);
    024	    }
    025	    fos.flush(); fos.close();
    026	    cis.close(); fis.close();
    027	  }
  2. The above Java program will encrypted PDF file. It takes the unencrypted PDF file (plain.pdf) and create encrypted.pdf (the encrypted file).
  3. Now with the encrypted.pdf, we use a PHP program to decrypt it:
    001	<?php
    002	  $secret_key   = "01234567890abcde";
    003	  $iv           = "fedcba9876543210";
    004	  $infile       = "encrypted.pdf";
    005	  $outfile      = "decrypted.pdf";
    006
    007	  $crypttext = file_get_contents($infile);
    008	  $plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128,
    009	                 $secret_key, $crypttext, MCRYPT_MODE_CBC, $iv);
    010
    011	  header('Content-Type: application/octet-stream');
    012	  header('Content-Length: ' . strlen($plaintext));
    013	  header('Content-Disposition: attachment; filename=' . ($outfile));
    014	  echo $plaintext;
    015	?>
  4. The PHP program takes the encrypted.pdf and force download the decrypted.pdf which should be the same as the plain.pdf.

One Response to “AES Interop Between PHP and Java (Part 4)”

  1. Mani Says:

    This is a very interesting post. Combine with the previous post, you presented a good overview of using AES on Java and PHP as well as inter-operation between them. Email me mani@digitalarmour.com.au if you are interested in some collaboration work.

Leave a Reply