1. 程式人生 > >PHP 異或 演算法

PHP 異或 演算法

PHP 異或 演算法

/**
     * PHP字串“異或”演算法
     * param    array   key
     * @param Request $request
     * @return mixed|string|void
     */
    public function setSecretKey(Request $request){
        $keyArr = $request->input('key');
        if(!is_array($keyArr) || empty($keyArr))
            return;
        foreach ($keyArr as $v){
            if(empty($v) || (strlen($v) != 32)){
                return;
            }
        }
        if(count($keyArr) == 1)
            return $keyArr[0];
        $arrLength = count($keyArr);
        $initKey = "00000000000000000000000000000000";
        $initKeyArr = str_split($initKey);
        for($i = 0;$i < $arrLength;$i++){
            $newKey = '';
            for($j = 0;$j < strlen($keyArr[$i]);$j++){
                $str = '';
                $tmpArr = str_split($keyArr[$i]);
                $tmpA = str_pad(base_convert($tmpArr[$j],16,2),4,0,STR_PAD_LEFT);
                $tmpB = str_pad(base_convert($initKeyArr[$j],16,2),4,0,STR_PAD_LEFT);
                for($k=0;$k<strlen($tmpA);$k++){
                    $str .=(intval($tmpA[$k]) ^ intval($tmpB[$k]));
                }
                $tmpOneKey = strtoupper(base_convert($str,2,16));
                unset($str);
                $newKey .= $tmpOneKey;
            }
            unset($initKeyArr);
            $initKeyArr = str_split($newKey);
        }
        return join($initKeyArr);
    }