I asked here a question why decryption AES java returns additional characters? about receiving additional characters when decrypting encrypted data. Thanks to a comment by Ebbe M. Pedersen, I now understand that the problem is not using the same padding mechanism in both PHP and Java Java code. So I changed the Java code to
Java code
public class encryption { private String iv = "fedcba9876543210";//Dummy iv (CHANGE IT!) private IvParameterSpec ivspec; private SecretKeySpec keyspec; private Cipher cipher; private String SecretKey = "0123456789abcdef";//Dummy secretKey (CHANGE IT!) public encryption() { ivspec = new IvParameterSpec(iv.getBytes()); keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES"); try { cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");//"AES/CBC/NoPadding" } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public byte[] encrypt(String text) throws Exception { if(text == null || text.length() == 0) throw new Exception("Empty string"); byte[] encrypted = null; try { cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); encrypted = cipher.doFinal(padString(text).getBytes()); } catch (Exception e) { throw new Exception("[encrypt] " + e.getMessage()); } return encrypted; } public byte[] decrypt(String code) throws Exception { if(code == null || code.length() == 0) throw new Exception("Empty string"); byte[] decrypted = null; try { cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); decrypted = cipher.doFinal(hexToBytes(code)); } catch (Exception e) { throw new Exception("[decrypt] " + e.getMessage()); } return decrypted; } public static String bytesToHex(byte[] data) { if (data==null) { return null; } int len = data.length; String str = ""; for (int i=0; i<len; i++) { if ((data[i]&0xFF)<16) str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF); else str = str + java.lang.Integer.toHexString(data[i]&0xFF); } return str; } public static byte[] hexToBytes(String str) { if (str==null) { return null; } else if (str.length() < 2) { return null; } else { int len = str.length() / 2; byte[] buffer = new byte[len]; for (int i=0; i<len; i++) { buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16); } return buffer; } } private static String padString(String source) { char paddingChar = ' '; int size = 16; int x = source.length() % size; int padLength = size - x; for (int i = 0; i < padLength; i++) { source += paddingChar; } return source; } }
Then I added the same PKCS5padding features to my PHP mcrypt class:
PHP mcrypt class
class MCrypt { private $iv = 'fedcba9876543210'; #Same as in JAVA private $key = '0123456789abcdef'; #Same as in JAVA function MCrypt() { } function encrypt($str) { //$key = $this->hex2bin($key); $iv = $this->iv; $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv); mcrypt_generic_init($td, $this->key, $iv); $encrypted = mcrypt_generic($td, $str); mcrypt_generic_deinit($td); mcrypt_module_close($td); return bin2hex($encrypted); } function decrypt($code) { //$key = $this->hex2bin($key); $code = $this->hex2bin($code); $iv = $this->iv; $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv); mcrypt_generic_init($td, $this->key, $iv); $decrypted = mdecrypt_generic($td, $code); mcrypt_generic_deinit($td); mcrypt_module_close($td); return utf8_encode(trim($decrypted)); } protected function hex2bin($hexdata) { $bindata = ''; for ($i = 0; $i < strlen($hexdata); $i += 2) { $bindata .= chr(hexdec(substr($hexdata, $i, 2))); } return $bindata; } function pkcs5_pad ($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); } function pkcs5_unpad($text) { $pad = ord($text{strlen($text)-1}); if ($pad > strlen($text)) return false; if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false; return substr($text, 0, -1 * $pad); }}
Now the current problem is sending / receiving UTF-8 characters, not how to decode / encode UTF-8 characters. When I send Arabic / Persian words containing, for example, more than 3 or less than 3 characters, it does not return anything. For example: If I send the word "خوب" (which has exactly 3 characters), I get "خوب", which is correct; but if I send مچکرم (which has 5 characters), I get nothing.
I found that the problem is that after decrypting the data in my php code, I did not use the decompress function, so I fixed:
Php code
<?php $data =file_get_contents('php://input'); $block_size=mcrypt_get_block_size("rijndael-128",'cbc'); require_once "encryption.php"; $etool=new MCrypt(); $data =$etool->decrypt($data); $data=$etool->pkcs5_unpad($data);// <------ using unpad function $data =json_decode($data, true); $data=$data["request"]; $etool=new MCrypt(); $data=$etool->pkcs5_pad($data,$block_size); $data=$etool->encrypt($data); $array=array('data'=>$data); echo json_encode($array);
And here is the Java code to get it
JSONObject j=new JSONObject(sb.toString());//sb is string builder result=j.get("data").toString(); result= new String(etool.decrypt( result ),"UTF-8"); result = new String(result.getBytes("ISO-8859-1")); Log.d("success remote ",result);
Now the problem is the opposite! I can get words containing more or less than three Persian / Arabic characters, but not words containing exactly 3 characters.
I think I should check: "Is debugging required?" but how to do that?