PHP 解密
这几天,碰到了需要PHP解密的工作,本来想直接调java去做的,后来想想不太好,还是老老实实查资料,慢慢搞定,经过几天的研究,真的搞好了首先,选择的mcrypt包来进行解密,
解密之前先要对加密的内容进行处理,因为内容格式是长度+内容,解析这个就花了好长时间
$sizeLength = 4;
$index = 0;
$keySize = getInt(bin2hex(substr($licenseInfo,$index,$sizeLength)));
$index += 4;
//echo "keySize: " . $keySize . "<br/>";
$keyInfo = getStr($keySize, substr($licenseInfo,$index,$keySize));
$index += $keySize;
$signatureLen = getInt(bin2hex(substr($licenseInfo,$index,$sizeLength)));
$index += 4;
//echo "signatureLen: " . $signatureLen . "<br/>";
$signatureInfo = getStr($signatureLen, substr($licenseInfo,$index,$signatureLen));
$index += $signatureLen;
$secretKeyLength = getInt(bin2hex(substr($licenseInfo, $index, $sizeLength)));
$index += 4;
//echo "secretKeyLength: " . $secretKeyLength . "<br/>";
$secretKeyInfo = getStr($secretKeyLength, substr($licenseInfo, $index, $secretKeyLength));
$index += $secretKeyLength;
$ivLength = getInt(bin2hex(substr($licenseInfo, $index, $sizeLength)));
$index += 4;
//echo "ivLength: " . $ivLength . "<br/>";
$ivInfo = getStr($ivLength, substr($licenseInfo, $index, $ivLength));
$index += $ivLength;
$cryptedlicenseLen = getInt(bin2hex(substr($licenseInfo, $index, $sizeLength)));
$index += 4;
//echo "cryptedlicenseLen: " . $cryptedlicenseLen . "<br/>";
$cryptedlicenseInfo = getStr($cryptedlicenseLen, substr($licenseInfo, $index, $cryptedlicenseLen));
$index += $cryptedlicenseLen;
function getStr($len, $data){
$str = "";
$type = "C".$len."str";
$crt_str = unpack($type,$data);
for($i = 1; $i <= $len; $i++){
$str .=chr($crt_str['str'.$i]);
}
return $str;
}
function getInt($tmp){
return hexdec($tmp);
}
java加密的方式就是另一个地方写的,这里读取,首先读取长度, substr也能直接来处理二进制的数据, 转成16进制在转成10进制,然后读取内容用unpack, 不知道,一开始试了很多次用unpack去得到长度,type是i/I/l/L,反正都试了,不行,但是用来处理字符就行了,。。。。。
// print_r( mcrypt_list_modes());
// echo mcrypt_enc_get_modes_name($cryptedlicenseInfo) . "<br/>";
// $block_size = mcrypt_get_block_size(MCRYPT_DES,MCRYPT_MODE_CBC);
// echo "blocksize: " . $block_size. "<br/>";
$decrypted = mcrypt_decrypt(MCRYPT_DES, $secretKeyInfo, $cryptedlicenseInfo, MCRYPT_MODE_CBC, $ivInfo);
// $decrypted = mcrypt_cbc(MCRYPT_3DES,$secretKeyInfo, $cryptedlicenseInfo, MCRYPT_DECRYPT, $ivInfo);
// echo "result : " . $decrypted . "<br/>";
// $td = mcrypt_module_open('3des','','cbc ','');
// mcrypt_generic_init($td, $secretKeyInfo, $ivInfo);
// echo "length: " . strlen($cryptedlicenseInfo) . "<br/>";
// $p_t = mdecrypt_generic($td, $cryptedlicenseInfo);
// echo "result : " . $p_t . "<br/>";
/* Clean up */
// mcrypt_generic_deinit($td);
// mcrypt_module_close($td);
直接考上解密的部分, 在mcrypt中解密,有三种方式(红的),碰到的问题: 一开始解析出来的字段不知道为什么,只有前8个字节,后来的死活不解密,无解啊,google了baidu了,就是没有,实在死的心都有了,后来才发现原来java的代码加密的时候用的Cipher是PCBC模式的,而mcrypt没有PCBC模式,只有CBC,我把java改成了CBC后就好了,吐血。
而算法好像没有影响,我不论是DES,还是3DES都可以的
还碰到了一个问题,就是PHP的调用嵌套有问题,不知道我写的不对还是,就像
$info = substr($data, strpos($data, ";")) 就是没反应,而
$index = strpos($data,";");
$info = substr($data,index);
分开了,就好的,。。。。。。
暂时就想到了这些,想到了再补
页:
[1]