数据传递过程中为了安全不篡改性,进行进制数加密解密

2017-9-14 guoweidong php开发

/**
* @param $num
* @return string
* 进制数转换
*/
function getHex($num)
{
$msg = (string)dechex($num);//把十进制转换为十六进制
// $msg = strtoupper($msg);
if (mb_strlen($msg) == 1) {
$msg = "0" . $msg;
}
return $msg;
}

/**
* @param string $src
* @return string
* 解密算法
*/
function php_en($src = '')
{
// $dest = '';
$key = 'ADDBYHGFFOVER';//ADDBYHGFFOVER
$keyPos = -1;
$srcLen = mb_strlen($src);
$keyLen = mb_strlen($key);

if ($keyLen == 0) {
$key = 'xj2006';
}
$range = 255;
$num = rand(0, $range);
$dest = getHex($num);
//十进制=>十六进制
if ($src == null) {
$src = '';
}
for ($i = 0; $i < $srcLen; $i++) {
//ascii码值+随机数再求余
$SrcAsc = (ord($src[ $i ]) + $num) % 255;
if ($keyPos < $keyLen - 1) {
$keyPos = $keyPos + 1;
} else {
$keyPos = 0;
}
$ss = ord($key[ $keyPos ]);
$SrcAsc = $SrcAsc ^ $ss;
$dest .= getHex($SrcAsc);
$num = $SrcAsc;
}
return trim($dest);
}

/**
* @param string $src
* @return null|string
* 加密算法
*/
function php_de($src = '')
{
$key = 'ADDBYHGFFOVER';
$keyPos = -1;
$result = "";
$srcLen = mb_strlen($src);
$keyLen = mb_strlen($key);
$TmpSrcAsc = "";
if($srcLen == 2){
return null;
}
if($keyLen == 0 ){
$key="xj2006";
}
try {
$offset = intval(hexdec(mb_substr($src, 0, 2)));
} catch (Exception $e) {
$offset = 0;
}
$srcPos = 3;
do{
try {
$s=mb_substr($src, $srcPos-1, 2);
$srcAsc = intval(hexdec($s));
} catch (Exception $e) {
$srcAsc=0;
}
if($keyPos < $keyLen-1){
$keyPos = $keyPos + 1;
}else{
$keyPos=0;
}
$ss = ord(mb_substr($key, $keyPos, 1));
$TmpSrcAsc = $srcAsc^$ss; //求异或
if($TmpSrcAsc <= $offset){
$TmpSrcAsc = 255 + $TmpSrcAsc - $offset;
}else{
$TmpSrcAsc = $TmpSrcAsc - $offset;
}
$d = chr(intval($TmpSrcAsc));
$result.=$d;
$offset = $srcAsc;
$srcPos = $srcPos + 2;
}while(!($srcPos >= $srcLen));
return $result;
}

网站备案号:京ICP备11043289号-1 北京市公安局网络备案 海1101084571
版权所有 北京育灵童科技发展有限公司 Copyright © 2002-2024 www.elight.cn, All Rights Reserved