<?php
//加密
function _checkPadding($padding, $type) {
if ($type == 'en') {
switch ($padding) {
case OPENSSL_PKCS1_PADDING :
$ret = true;
break;
default :
$ret = false;
}
} else {
switch ($padding) {
case OPENSSL_PKCS1_PADDING :
case OPENSSL_NO_PADDING :
$ret = true;
break;
default :
$ret = false;
}
}
return $ret;
}
function encrypt($gcPubKey,$data, $code = 'base64', $padding = OPENSSL_PKCS1_PADDING) {
if (! _checkPadding($padding, 'en'))
echo 'padding error' ;
$len = "117";
$strArray = str_split ( $data, $len );
$ret = false;
foreach ( $strArray as $cip ) {
if (openssl_public_encrypt ( $cip, $result, $gcPubKey, $padding )) {
$ret .= $result;
}
}
$s = $ret;
$hex = _encode ( $s, "hex" );
$ret = _encode ( $ret, "base64" );
return $ret;
}
function _encode($data, $code) {
switch (strtolower ( $code )) {
case 'base64' :
$data = base64_encode ( $data );
break;
case 'hex' :
$data = bin2hex ( $data );
break;
case 'bin' :
default :
}
return $data;
}
//将XML转为array
function xmlToArray($xml)
{
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
}
//解密
function decrypt($data, $code = 'base64', $padding = OPENSSL_PKCS1_PADDING, $rev = false,$priKey) {
$ret = false;
$data = _decode ( $data, $code );
if (! _checkPadding ( $padding, 'de' ))
echo 'padding error' ;
if ($data != false) {
$len = "128";
$strArray = str_split ( $data, $len );
$result = '';
foreach ( $strArray as $cip ) {
if (openssl_private_decrypt ( $cip, $result, $priKey, $padding )) {
$ret .= $result;
}
}
}
return $ret;
}
function _decode($data, $code) {
switch (strtolower ( $code )) {
case 'base64' :
$data = base64_decode ( $data );
break;
case 'hex' :
$data = _hex2bin ( $data );
break;
case 'bin' :
default :
}
return $data;
}
function _hex2bin($hex = false) {
$ret = $hex !== false && preg_match ( '/^[0-9a-fA-F]+$/i', $hex ) ? pack ( "H*", $hex ) : false;
return $ret;
}
//将XML转为array
private function xmlToArray($xml)
{
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
}