AES Interop Between PHP and Java (Part 1)

… 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.
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • digg
  • del.icio.us
  • Slashdot
  • Netscape
  • YahooMyWeb
  • Furl

12 Responses to “AES Interop Between PHP and Java (Part 1)”

  1. Amit Agarwal Says:

    Hi..

    Is it possible to do other way round ? encypting in Java and decrypting in PHP ?

    Thanks

  2. Marc Liyanage Says:

    Hey thanks a lot, exactly what I needed, exactly when I needed it :-)

    I really wish mcrypt had PKCS#5 padding…

  3. linus Says:

    Marc: Thanks, I wish mcrypt has PKCS5 padding too. I think someone wrote a function for it. Check out http://www.php.net/mcrypt (comment from duerra_NOT_THIS_ at pushitlive dot net).

    Amit: I have been away for a long Chinese New Year holidays and finally get around to do a post of what you are looking for, encrypting in Java and decrypting in PHP. Check out my new post at http://www.propaso.com/blog/2007/03/12/aes-interop-between-php-and-java-part-2-working-the-other-way-around/

  4. robi Says:

    i tried to encrypt with very long text
    but the result is error
    it said that the string is too long
    can u help me???

  5. robi Says:

    sorry with the 1st post
    i mean decrypt not encrypt

  6. linus Says:

    I assume that you are encrypting with PHP and decrypting with Java. Could you give an idea of how long is your string (in term of number of characters)??

  7. robi Says:

    yo’re right i’m encrypting with php and decrypt with java..
    i copy the hexadesimal string from encrypted file
    the string long is 507808 character

  8. robi Says:

    this is the string
    1a3d8846133fc5……1ebcd6f2544c777c1779

  9. Fun Things in Life » Blog Archive » AES Interop Between PHP and Java (Part 3) Says:

    […] Problem: Part 1 and Part 2 has been quite interesting. I was thinking of what to do next and Robi Ilham asked me to […]

  10. Fun Things in Life » Blog Archive » AES Interop Between PHP and Java (Part 2) Says:

    […] Problem: In a previous post, I show how to use AES in PHP to encrypt a message and decrypt it in Java. Then Amit asked if it […]

  11. Ken Beukelman Says:

    Should the final parameter in the call to mcrypt_module_open be “” (rather than $iv)?

  12. linus Says:

    In Java, we set the initial vector to

    IvParameterSpec ivSpec = new IvParameterSpec(”fedcba9876543210″.getBytes());

    for decryption, so the initial vector in PHP for encryption should be the corresponding

    mcrypt_generic_init($td, $secret_key, $iv);

    where $iv is set to “fedcba9876543210″

Leave a Reply