Archive for January, 2007

AES Interop Between PHP and Java (Part 1)

Saturday, January 27th, 2007

… Life is never easy, learning takes time. Hope this will help someone out there …

The Problem: I want to encrypt a message in PHP using AES and then take it to a Java program to decrypt it.

Without all the knowledge about AES, Key, CBC, ECB, etc, etc… I will present a simple solution. Keep in mind, these are bits and pieces, so that I wouldn’t take all the fun out of you. I will just show you how to encrypt and decrypt and you can implement other things in between so that you can also have the fun.

The Solution:

  1. We are using mcrypt with PHP. The encryption program in PHP:
    001	<?php
    002	  $cipher     = "rijndael-128";
    003	  $mode       = "cbc";
    004	  $plain_text = "Hello World";
    005	  $secret_key = "01234567890abcde";
    006	  $iv         = "fedcba9876543210";
    007
    008	  td = mcrypt_module_open($cipher, "", $mode, $iv);
    009	  mcrypt_generic_init($td, $secret_key, $iv);
    010	  $cyper_text = mcrypt_generic($td, $plain_text);
    011	  echo bin2hex($cyper_text);
    012	  mcrypt_generic_deinit($td);
    013	  mcrypt_module_close($td);
    014	?>
  2. The output from the above program should be “ac5c3404f57a5061f36a694eb5d56214″
  3. We just take the output and decrypt it over in the following Java program:
    001	import javax.crypto.spec.IvParameterSpec;
    002	import javax.crypto.Cipher;
    003	import java.security.MessageDigest;
    004	import java.security.NoSuchAlgorithmException;
    005	import java.lang.Exception;
    006	import javax.crypto.spec.SecretKeySpec;
    007	import javax.crypto.SecretKey;
    008	import java.io.IOException;
    009
    010	public class tester {
    011	  public static byte[] hexToBytes(String str) {
    012	    if (str==null) {
    013	      return null;
    014	    } else if (str.length() < 2) {
    015	      return null;
    016	    } else {
    017	      int len = str.length() / 2;
    018	      byte[] buffer = new byte[len];
    019	      for (int i=0; i<len; i++) {
    020	        buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
    021	      }
    022	      return buffer;
    023	    }
    024	  }
    025
    026	  public static void main(String [] args) throws Exception {
    027	    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    028	    SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
    029	    IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
    030	    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    031	    byte[] outText = cipher.doFinal(hexToBytes("ac5c3404f57a5061f36a694eb5d56214"));
    032	    System.out.println(new String(outText).trim());
    033	  }
    034	}
  4. The output from the Java program should be “Hello World”. Take note that on line 31, we put in the output from PHP.