首页 >php教程 >PHP源码 >可加密64编码解码,用于对ID的编码解码

可加密64编码解码,用于对ID的编码解码

PHP中文网
PHP中文网原创
2016-05-25 17:06:341283浏览

可加密64编码解码,用于对ID的编码解码

<?php
/**
 * 可加密64编码解码,用于对ID的编码解码
*/
class code {
 private $key = null;
 function __construct($key) {
 $this->key = $key;
}
/**
 * 对数字编码
*/
 function encode($value) {
 $x = sprintf("%d", intval($value) ^ intval($this->key));
 $y = $this->encode_b64(intval($x));
 return $y;
}
/**
*解码
*/
 function decode($pwd) {
 $pwd = $this->decode_b64($pwd);
 $re = strval(intval($pwd) ^ intval($this->key));
 return $re;
}
/**
 * 重置密钥
*/
 function reset_key($key) {
 $this->key = $key;
}
/**
 * 64进位编码
*/
 public function encode_b64($n) {
 $table = &#39;0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_&#39;;
 $result = array();
 $temp = $n;
 if (0 == $temp) {
 $result[] = &#39;0&#39;;
 } else {
 while (0 < $temp) {
 $result[] = $table[$temp % 64];
 $temp = intval($temp / 64);
}
}
//反转数组
krsort($result);
 return implode(&#39;&#39;, $result);
}
/**
 * 64进位解码
*/
 public function decode_b64($str) {
 $table = array("0"=> 0,"1"=> 1,"2"=> 2,"3"=> 3,"4"=> 4,"5"=> 5,
"6"=> 6,"7"=> 7,"8"=> 8,"9"=> 9,
"a"=> 10,"b"=> 11,"c"=> 12,"d"=> 13,"e"=> 14,"f"=> 15,"g"=> 16,
"h"=> 17,"i"=> 18,"j"=> 19,"k"=> 20,"l"=> 21,"m"=> 22,"n"=> 23,
"o"=> 24,"p"=> 25,"q"=> 26,"r"=> 27,"s"=> 28,"t"=> 29,"u"=> 30,
"v"=> 31,"w"=> 32,"x"=> 33,"y"=> 34,"z"=> 35,
"A"=> 36,"B"=> 37,"C"=> 38,"D"=> 39,"E"=> 40,"F"=> 41,"G"=> 42,
"H"=> 43,"I"=> 44,"J"=> 45,"K"=> 46,"L"=> 47,"M"=> 48,"N"=> 49,
"O"=> 50,"P"=> 51,"Q"=> 52,"R"=> 53,"S"=> 54,"T"=> 55,"U"=> 56,
"V"=> 57,"W"=> 58,"X"=> 59,"Y"=> 60,"Z"=> 61,
"-"=> 62,"_"=> 63);
 $result = 0;
 foreach (range(0, strlen($str) - 1) as $i) {
 $result *= 64;
 $result += $table[$str[$i]];
}
 return $result;
}
}
$d = new code(&#39;123123&#39;);
echo $d->encode(222584587),"n";
echo $d->decode(&#39;dhr_U&#39;),"n";
$d = new code(&#39;333333&#39;);
echo $d->encode(222584587),"n";
echo $d->decode(&#39;dgkAu&#39;),"n";


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn