Java – PHP and JAVA encryption and decryption routines

PHP and JAVA encryption and decryption routines… here is a solution to the problem.

PHP and JAVA encryption and decryption routines

I have the following PHP routine to encrypt my communication with the client:

public static function encrypt($input, $key) {
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); 
        $input = AES::pkcs5_pad($input, $size); 
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, ''); 
        $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND); 
        mcrypt_generic_init($td, $key, $iv); 
        $data = mcrypt_generic($td, $input); 
        $data = base64_encode($data); 
        return $data; 

and the following Java rotuine to decrypt my communication with the server:

public static String decrypt(String input, String key) {
        byte[] output = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(Base64.decode(input,Base64.NO_WRAP));
        } catch (Exception e) {
        return new String(output);

Why does the decryption routine below throw an exception?

java.lang.IllegalArgumentException: bad base-64

EDIT: After hardcoding the string into the code, I get a BadPaddingException.

My decryption function input:

 wrmRa2hAoseNOev6/ascapxkLQRGX/GW3DQm3ETwBH7gJm1NetkgGFzgY4kZTE10Tv45YIcy/xoodq/GumSY5hsao1s4bkuKXZeim/IDTVr3elrqX13b81/XE5iB3iJrAqny2dQ5SsWso0lUcAZGS2Wls/ lTeQiIKXEaOh7iZZ3xOtM6633iNcoiFxEnX5A0dMrdRNEOkmQ3UnQmuIGTSv0RLKuPv5r5dplGZ3N2LMMpoB0AMu3DSXFEdiD4XN49


You may need to use:

Base64.decode(input,Base64.NO_WRAP| Base64.URL_SAFE)

You may also need different combinations of logos.

It also depends on how you get the base64 string. If transmitted from a URL or other online source, sometimes “+” translates to “” (spaces).

Related Problems and Solutions