When is padding required for encryption?

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?

+2
source share
2 answers
 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); } 

This code uses PHP string functions that operate on a raw binary by default and ignore the encoding.

Mixing your decrypted messages with utf8_encode() doesn't really make sense. This function reassigns ISO-8559-1 codes (i.e. 0x00 through 0xFF ) to UTF-8 code points (i.e. 0x00 through 0x7f , then 0xc280 through 0xc2bf and 0xc380 through 0xc3bf ).

Since PHP runs on the raw binary by default, you do not need to apply this conversion at all.

Note. I said the default. PHP has a very silly function called function overload , which is controlled by the mbstring.func_overload PHP.ini directive. If you use this function, you need to rewrite each piece of cryptographic code that should measure and / or fragments of the string not to use strlen() , substr() , etc.

Defuse Security has published and maintains a secure, authenticated PHP encryption library that contains replacements for these functions that resist function overloading .


Security Notice

First: Your cryptocode does not work . In other words: NOT SAFE .

Second: Avoid using mcrypt for anything if you can help it .

If you just need your data for wire encryption, just use TLS . Attempting to reinvent the wheel here will simply lead to disaster.

However, if (for example) you need peer-to-peer encryption on top of TLS (for example, so that your server never sees data), do not roll your own. Instead, choose a secure PHP cryptography library . If you need one that works cross-platform, use libsodium .

+1
source

the problem is the misuse of the un-padding function in php code. in fact, when encrypting data in java, several times, because the text does not correspond to the block , it uses an addition for it, and if the text is suitable, it does not. in PHP code, if padding was used in java encryption, un-padding is done correctly. but if the text does not need to be supplemented with java encryption, the un-padding PHP function returns null, and null is passed to the $ data variable. so i get nothing !!! by changing a few lines of php code everyone thinks that start working correctly.

Code causing the problem:

 $data=$etool->pkcs5_unpad($data);// in some cases null is retuned $data =Json_decode($data,true); 

the correct version of the code: the problem is fixed.

 $padding=$etool->pkcs5_unpad($data); if($padding!="") { $data=$padding; } $data =json_decode($data, true); 
0
source

Source: https://habr.com/ru/post/1242339/


All Articles