Discuz的加密与解密函数authcode
authcode()并不是PHP的内置函数,它是康盛开发的一个使用异或运算进行加密和解密的函数,可以说这是康盛对中国的PHP界作出的重大贡献
康盛自己的产品如Discuz,UCenter等以及许多使用PHP的中国公司都用这个函数进行加密,
在同步登录(从项目登录到UCenter)的过程中,authcode()把用户的登录信息进行加密,因为没有加密的数据在传递过程中容易被截取,这样会暴露了用户的信息,authcode()的作用就是给传递的数据提供加密保护作用。
在数据到达终端(UCenter)时authcode()再把加密的数据进行反向解密,还原数据。
通过下面的程序演示会让我们更了解authcode()以及同步登录的原理
<?php
define('UC_KEY', 'abc123456');//整合程序的通讯密钥
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
$ckey_length = 4;
$key = md5($key ? $key : UC_KEY);
$keya = md5(substr($key, 0, 16));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
$cryptkey = $keya.md5($keya.$keyc);
$key_length = strlen($cryptkey);
$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
$string_length = strlen($string);
$result = '';
$box = range(0, 255);
$rndkey = array();
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
}
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;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if($operation == 'DECODE') {
if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
return substr($result, 26);
} else {
return '';
}
} else {
return $keyc.str_replace('=', '', base64_encode($result));
}
}
echo authcode('www.w3note.com', 'ENCODE', 'abc123456').'<br>';
$keycode='8207otGoCcELKJX1/Puhf/yHqmpUq91JXUFOXZoA7B6bWXVMIlSQi53GYQ';
echo authcode($keycode,'DECODE' , $key = 'abc123456');
?>
先来了解一下有关authcode()的四个参数,一般情况下只用到前三个:
$string 提供需要加密的字符串
$operation 加密方式,ENCODE是加密,DECODE是解密
$key 密钥,在整合程序时填写的密钥。
在上现的程序中,$keycode是加密后的字符串,这个程序很有趣,同样的字符串如“www.w3note.com”,每次运行程序后得到的$keycode都是不同的,但是万变不离其踪,不管$keycode是怎样变化,被解密后都被还原为原来的样子。
转自:http://w3note.com/web/76.html
Leave a comment
0 Comments.
