MyQEE\Server\RPC\Server::rc4 PHP Метод

rc4() защищенный статический Метод

优化版rc4加密解密
protected static rc4 ( string $string, string $isDecode = true, string $key = null, number $expiry ) : string
$string string
$isDecode string
$key string
$expiry number
Результат string
    protected static function rc4($string, $isDecode = true, $key = null, $expiry = 0)
    {
        $cKeyLength = 4;
        $key = md5($key ?: __DIR__);
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $cKeyLength ? $isDecode === true ? substr($string, 0, $cKeyLength) : substr(md5(microtime()), -$cKeyLength) : '';
        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);
        $string = $isDecode == true ? base64_decode(substr($string, $cKeyLength)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);
        $result = '';
        $box = range(0, 255);
        $randKey = [];
        for ($i = 0; $i <= 255; $i++) {
            $randKey[$i] = ord($cryptkey[$i % $key_length]);
        }
        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $randKey[$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 ($isDecode == true) {
            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 . base64_encode($result);
        }
    }