博客列表 >关于支付时rsa加密解密的函数

关于支付时rsa加密解密的函数

WZY的博客
WZY的博客原创
2018年01月11日 15:04:42692浏览

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

    }



声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议