function String2Hex($string){
$hex='';
for ($i=0; $i < strlen($string); $i++){
$hex .= dechex(ord($string[$i]));
}
return $hex;
}
//-------------------------
// 注意:签名KEY换成自己的appkey
//--------------------------
public function MakeSign($params)
{
//签名步骤一:按字典序排序参数
ksort($params);
$string = $this->ToUrlParams($params);
//签名步骤二:在string后加入KEY
$string = $string . "&key=签名KEY";
//签名步骤三:MD5加密
$string = md5($string);
//签名步骤四:所有字符转为大写
$result = $string; //strtoupper($string);
return $result;
}
/**
* 格式化参数格式化成url参数
*/
public function ToUrlParams($params)
{
$buff = "";
foreach ($params as $k => $v)
{
if($k != "sign" && $v != "" && !is_array($v)){
$buff .= $k . "=" . $v . "&";
}
}
$buff = trim($buff, "&");
return $buff;
}
public function encrypt($input, $key) {
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$input_content = $this->pkcs5_pad($input, $size);
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$data = mcrypt_generic($td, $input_content);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$data = bin2hex($data);
return $data;
}
private function pkcs5_pad($text, $blocksize) {
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
public function decrypt($sStr, $sKey) {
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $sKey, pack("H*",$sStr), MCRYPT_MODE_ECB);
$dec_s = strlen($decrypted);
$padding = ord($decrypted[$dec_s-1]);
$decrypted = substr($decrypted, 0, -$padding);
return $decrypted;
}
// 加密流程
$req["biz_content"] = encrypt(json_encode($biz_content), "换成aes密钥");
$req["sign"] = $this->MakeSign($req);
$reqText = json_encode($req);
// 解密
$biz_content = decrypt($res["biz_content"], "换成aes密钥"), true);
PHP 与 JAVA AES互通
最新推荐文章于 2024-04-24 10:34:23 发布