PHP AES with mcrypt and decrypt with Java

Some important tips for building php webservice or php web api  and  requested by Java Client.

  1. PHP user mcrypt library for Cipher implements. like this.  $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128,”,MCRYPT_MODE_CBC,”);  While many samples code use MCRYPT_RIJNDAEL_256 . It’s robust and very safe but not  supported by Java Cipher Code.
    • The algorithms are specified by java Cipher about AES including
    • AES/CBC/NoPadding (128)
      AES/CBC/PKCS5Padding (128)
      AES/ECB/NoPadding (128)
      AES/ECB/PKCS5Padding (128)
    • Notice above algorithms , all is 128bit . So MCRYPT_RIJNDAEL_128  should by used by php
  2. the secret key used by mcrypt_generic_init($td,_secret_key,$iv) should be 16 Bytes  . Key size is 128 bits.
  3. IV must be shared by PHP and Java Code.
  4. when encrypt with mcrypt_generic($td, $input) . $input will by padding by mcrypt by NULL. While decrypt code by Java Should be Cipher.getInstance("AES/CBC/NoPadding", "SunJCE").  NoPadding will padding NULL too.
  5. More detail code . Please refer to this article 

Leave a Reply

Your email address will not be published. Required fields are marked *