<?php
/**
*加密解密数据
* @param $string:要操作的字符串
* @param $key:加密/解密key
* @param $operation:操作类型(ENCODE加密;DECODE解密)
*/
//define('string','消息标题');// update by xuhaitao
// define('key','123456abcdef');// update by xuhaitao
$string='abcd';// update by xuhaitao
$key='123456abcdef';// update by xuhaitao
$operation='ENCODE'; $key = md5($key);
$key_length = strlen($key);
if($key_length == 0) {
return false;
}
// 三目运算符 判断是否是加密和解密
$string = $operation == 'DECODE' ? base64_decode($string) : substr(md5($string.$key), 0, 8).$string;
// add by xuhaitao start
// 输出加密,解密的 字符串
// add by xuhaitao end
$string_length = strlen($string);
// 定义两个数组
$rndkey = $box = array();
// 定义一个返回结果
$result = '';
for($i = 0; $i <= 255; $i++) {
//
$rndkey[$i] = ord($key[$i % $key_length]);
// 为box 数组赋值 0-255
$box[$i] = $i;
}
// 交换
for($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
} for($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
// 输出结果
echo(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
//echo($result);
if($operation == 'DECODE') {
if(substr($result, 0, 8) == substr(md5(substr($result, 8).$key), 0, 8)) {
//echo substr($result, 8);
} else {
// echo '123';
}
} else {
// echo str_replace('=', '', base64_encode($result));
}
?>
http://writecodeonline.com/php/