3

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?

4

1 回答 1

0

确保您的密钥由相同的字节组成(字符串的编码可能不同),并为它提供一个用零填充的 IV。ECB 模式不使用 IV(并且 PHP 手册指定了这么多),但如果你给它一个默认值,它会全部为零 - IV 将与第一个纯文本块进行异或,因此将其设置为全零将取消该操作。此外,请确保输入的密码数据相同。首先忽略填充,您应该能够在取消填充之前检查结果是否正确。

于 2012-04-18T00:17:38.147 回答