phpcms v9 sys_auth函數(shù)加密原理

字號:


    假設變量$a,$b,$c=$a^$b(變量a異或變量b),
    所以我們有$a=$b^$c , $b=$a^$c
    以上是異或邏輯的應用,(題外話:如何在不使用第3個變量的情況下,交換變量$a,$b的值呢?)
    正題:
    可以把變量$a看成是明文(需加密的字符串),變量$b看成是密鑰(自己定義),變量$c看成是密文(發(fā)送到客戶端在網(wǎng)上傳輸?shù)?。
    當然上面只是基本原理,加密絕不是就簡單的異或字符串就行。
    為了使算法更不易破解sys_auth函數(shù)對密鑰進行了一個加密:
    $key_length = 4;
    $key = md5($key);
    $fixedkey = md5($key);
    $egiskeys = md5(substr($fixedkey, 16, 16));
    $runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
    $keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
    對明文也插入一些片段,并用base64進行了編碼。
    function sys_auth($string, $operation = 'ENCODE', $key = 'hi', $expiry = 0) {$key_length = 4;$key = md5($key);$fixedkey = md5($key);$egiskeys = md5(substr($fixedkey, 16,
    16));$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));$string
    = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));//10位密文過期信息+16位明文和密鑰生成的密文驗證信息+明文$i = 0; $result = '';$string_length = strlen($string);for
    ($i = 0; $i < $string_length; $i++){$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));}if($operation == 'ENCODE') {return $runtokey . str_replace('=', '', base64_encode($result));} else {if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time()
    > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {return substr($result, 26);} else {return '';}}}
    function sys_auth($string, $operation = 'ENCODE', $key = 'hi', $expiry = 0) {$key_length = 4;$key = md5($key);$fixedkey = md5($key);$egiskeys = md5(substr($fixedkey,
    16, 16));$runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';$keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));$string
    = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));//10位密文過期信息+16位明文和密鑰生成的密文驗證信息+明文$i = 0; $result = '';$string_length = strlen($string);for
    ($i = 0; $i < $string_length; $i++){$result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));}if($operation == 'ENCODE') {return $runtokey . str_replace('=', '', base64_encode($result));} else {if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time()
    > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {return substr($result, 26);} else {return '';}}}