DES / ECB / PKCS5在PHP中的解密 [英] DES/ECB/PKCS5Padding decryption in PHP

查看:292
本文介绍了DES / ECB / PKCS5在PHP中的解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用PHP(或Javascript)解密一些服务调用。我一直在努力完成这一切,但是我一直无法正确解密。

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.

作为参考,服务提供商向我发送以下信息在Java中解密示例代码:

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);

但坦率地说,我相信我用$ iv creationg和$ keyword设置(或者可能使用$数据或$解密类型?)。 pkcs5_unpad功能如下:

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);
}

我不仅仅是php上的noob,还有加密技术。你可以帮我解决这个问题吗?

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

推荐答案

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

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.

这篇关于DES / ECB / PKCS5在PHP中的解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆