DES/ECB/PKCS5Padding decryption in PHP

2020-07-22 10:00发布

问题:

I'm in the need of decrypting with PHP (or Javascript) some service calls. I've spent all the day trying to accomplish, this, but I've been unable to decrypt it properly.

As a reference, the service provider sent me the following decryption sample code in Java:

DESKeySpec dks = new DESKeySpec("keyword".getBytes()); 
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(dks);

Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
SecureRandom sr = new SecureRandom();  
cipher.init( Cipher.DECRYPT_MODE, key ,sr); 

byte b[] = response.toByteArray();      
byte decryptedData[] = cipher.doFinal( b );

I think I'm in the correct path by using:

$td = mcrypt_module_open(MCRYPT_DES, '', 'ecb', '');
$iv_size = mcrypt_enc_get_iv_size($td);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = substr($keyword, 0, mcrypt_enc_get_key_size($td));
mcrypt_generic_init($td, $key, $iv);
$decrypted = mdecrypt_generic($td, $data);
$decrypted = pkcs5_unpad($decrypted);

But, frankly, I'm sure I'm messing everything with the $iv creationg and $keyword setup (or maybe with $data or $decrypted types?). The pkcs5_unpad function is as follows:

function pkcs5_unpad($text)
{
   $pad = ord($text{strlen($text)-1});
   if ($pad > strlen($text)) return false;
   return substr($text, 0, -1 * $pad);
}

I'm not only a noob on php, but also on cryptography techniques... could you please help me to solve this issue?

回答1:

Make sure your key consists of the same bytes (strings may be encoded differently) and feed it a IV filled with zero's. ECB mode does not use an IV (and the PHP manual specifies as much), but if you do give it one default it to all zero's - the IV will be XOR'ed with the first plain text block, so setting it to all zero's will cancel out that operation. Also, make sure that the input cipher data is the same. Ignore the padding in the first instance, you should be able to check if the result is correct before unpadding.