Generate pseudo random bytes as last resort

@param $bytesToReturn
@return string
779525
protected static function generateRandomBytesFallback($bytesToReturn) {
		$bytes = '';
			// We initialize with somewhat random.
		$randomState = $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] . base_convert(memory_get_usage() % pow(10, 6), 10, 2) . microtime() . uniqid('') . getmypid();
		while (!isset($bytes{$bytesToReturn - 1})) {
			$randomState = sha1(microtime() . mt_rand() . $randomState);
			$bytes .= sha1(mt_rand() . $randomState, TRUE);
		}
		return $bytes;
	}
596066
public function EntryRead($Bytes = -1)
    {
        $Actual = $this->EntryActualSize();
        if ($Bytes < 0 || $Bytes > $Actual) {
            $Bytes = $Actual;
        }
        return substr($this->Data, $this->Offset + 512, $Bytes);
    }
976860
public static function randomBytes($length = 16)
    {
        if (function_exists('random_bytes')) {
            $bytes = random_bytes($length);
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
            $bytes = openssl_random_pseudo_bytes($length, $strong);
            if (false === $bytes || false === $strong) {
                throw new RuntimeException('Unable to generate random string.');
            }
        } else {
            throw new RuntimeException('OpenSSL extension is required for PHP 5 users.');
        }

        return $bytes;
    }
373705
public function EntryRead($Bytes = -1)
    {
        $Actual = $this->EntryActualSize();
        if ($Bytes < 0 || $Bytes > $Actual) {
            $Bytes = $Actual;
        }
        $Output = '';
        if ($Bytes > 0 && ($Stream = $this->RarEntry->getStream())) {
            $Output .= fread($Stream, $this->RarEntry->getUnpackedSize());
            fclose($Stream);
        }
        return $Output;
    }
320322
public function generate()
    {
        if ($this->_getOpenSSLFunctionalityChecker()->isOpenSslRandomBytesGeneratorAvailable()) {
            $sSalt = bin2hex(openssl_random_pseudo_bytes(16));
        } else {
            $sSalt = $this->_customSaltGenerator();
        }

        return $sSalt;
    }
326181
public static function generateCryptoKey($length)
    {
        // PHP>=7.0
        if (function_exists('random_bytes')) {
            return random_bytes($length);
        }
        
        $buf = openssl_random_pseudo_bytes($length, $secure);

        if ($buf !== false) {
            return $buf;
        }

        throw new \Exception('PRNG failure');
    }
1346634
private function formatBytes($bytes, $precision = 2)
    {
        $unit = array('B','KB','MB','GB','TB','PB','EB');

        if (!$bytes) {
            return "0 B";
        }

        return @round(
            $bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision
        ).' '.$unit[$i];
    }
1156490
final static public function sizeBytesToText (int $bytes=0) : string
	{
		if ($bytes >= pow(1024,8)) 			return number_format($bytes / pow(1024,8), 2) . ' YB';
		elseif ($bytes >= pow(1024,7)) 		return number_format($bytes / pow(1024,7), 2) . ' ZB';
		elseif ($bytes >= pow(1024,6)) 		return number_format($bytes / pow(1024,6), 2) . ' EB';
		elseif ($bytes >= pow(1024,5)) 		return number_format($bytes / pow(1024,5), 2) . ' PB';
		elseif ($bytes >= pow(1024,4)) 		return number_format($bytes / pow(1024,4), 2) . ' TB';
		elseif ($bytes >= pow(1024,3)) 		return number_format($bytes / pow(1024,3), 2) . ' GB';
		elseif ($bytes >= pow(1024,2)) 		return number_format($bytes / pow(1024,2), 2) . ' MB';
		elseif ($bytes >= pow(1024,1)) 		return number_format($bytes / pow(1024,1), 2) . ' KB';		
		elseif ($bytes > 1) 				return $bytes . ' bytes';		
		elseif ($bytes <= 1) 				return $bytes . ' byte';
	}
127891
public static function genRandomBytes($length = 16)
    {
        if (function_exists('random_bytes')) {
            return random_bytes($length);
        }

        $sslStr = '';

        /*
         * If a secure randomness generator exists use it.
         */
        if (function_exists('openssl_random_pseudo_bytes')) {
            $sslStr = openssl_random_pseudo_bytes($length, $strong);

            if ($strong) {
                return $sslStr;
            }
        }

        /*
         * Collect any entropy available in the system along with a number
         * of time measurements of operating system randomness.
         */
        $bitsPerRound = 2;
        $maxTimeMicro = 400;
        $shaHashLength = 20;
        $randomStr = '';
        $total = $length;

        // Check if we can use /dev/urandom.
        $urandom = false;
        $handle = null;

        if (@is_readable('/dev/urandom')) {
            $handle = @fopen('/dev/urandom', 'rb');

            if ($handle) {
                $urandom = true;
            }
        }

        while ($length > strlen($randomStr)) {
            $bytes = ($total > $shaHashLength) ? $shaHashLength : $total;
            $total -= $bytes;
            /*
             * Collect any entropy available from the PHP system and filesystem.
             * If we have ssl data that isn't strong, we use it once.
             */
            $entropy = mt_rand() . uniqid(mt_rand(), true) . $sslStr;
            $entropy .= implode('', @fstat(fopen(__FILE__, 'r')));
            $entropy .= memory_get_usage();
            $sslStr = '';

            if ($urandom) {
                stream_set_read_buffer($handle, 0);
                $entropy .= @fread($handle, $bytes);
            } else {
                /*
                 * There is no external source of entropy so we repeat calls
                 * to mt_rand until we are assured there's real randomness in
                 * the result.
                 *
                 * Measure the time that the operations will take on average.
                 */
                $samples = 3;
                $duration = 0;

                for ($pass = 0; $pass < $samples; ++$pass) {
                    $microStart = microtime(true) * 1000000;
                    $hash = sha1(mt_rand(), true);

                    for ($count = 0; $count < 50; ++$count) {
                        $hash = sha1($hash, true);
                    }

                    $microEnd = microtime(true) * 1000000;
                    $entropy .= $microStart . $microEnd;

                    if ($microStart >= $microEnd) {
                        $microEnd += 1000000;
                    }

                    $duration += $microEnd - $microStart;
                }

                $duration = $duration / $samples;

                /*
                 * Based on the average time, determine the total rounds so that
                 * the total running time is bounded to a reasonable number.
                 */
                $rounds = (int) (($maxTimeMicro / $duration) * 50);

                /*
                 * Take additional measurements. On average we can expect
                 * at least $bitsPerRound bits of entropy from each measurement.
                 */
                $iter = $bytes * (int) ceil(8 / $bitsPerRound);

                for ($pass = 0; $pass < $iter; ++$pass) {
                    $microStart = microtime(true);
                    $hash = sha1(mt_rand(), true);

                    for ($count = 0; $count < $rounds; ++$count) {
                        $hash = sha1($hash, true);
                    }

                    $entropy .= $microStart . microtime(true);
                }
            }

            $randomStr .= sha1($entropy, true);
        }

        if ($urandom) {
            @fclose($handle);
        }

        return substr($randomStr, 0, $length);
    }
142164
public static function toHuman($byteSize)
    {
        $kB = 1024;
        $MB = $kB * 1024;
        $GB = $MB * 1024;
        $TB = $GB * 1024;
        if ($byteSize > $TB) {
            return sprintf('%0.2f TiB', $byteSize / $TB);
        }
        if ($byteSize > $GB) {
            return sprintf('%0.2f GiB', $byteSize / $GB);
        }
        if ($byteSize > $MB) {
            return sprintf('%0.2f MiB', $byteSize / $MB);
        }

        return sprintf('%0.0f kiB', $byteSize / $kB);
    }
879847
public static function size_format($bytes, $decimals = 0)
    {
        $bytes = floatval($bytes);

        if ($bytes < 1024) {
            return $bytes . ' B';
        } elseif ($bytes < pow(1024, 2)) {
            return number_format($bytes / 1024, $decimals, '.', '') . ' KiB';
        } elseif ($bytes < pow(1024, 3)) {
            return number_format($bytes / pow(1024, 2), $decimals, '.', '') . ' MiB';
        } elseif ($bytes < pow(1024, 4)) {
            return number_format($bytes / pow(1024, 3), $decimals, '.', '') . ' GiB';
        } elseif ($bytes < pow(1024, 5)) {
            return number_format($bytes / pow(1024, 4), $decimals, '.', '') . ' TiB';
        } elseif ($bytes < pow(1024, 6)) {
            return number_format($bytes / pow(1024, 5), $decimals, '.', '') . ' PiB';
        } else {
            return number_format($bytes / pow(1024, 5), $decimals, '.', '') . ' PiB';
        }
    }
1167899
public static function filesize($bytes)
    {
        $precision = (($bytes % 1024) === 0 || $bytes <= 1024) ? 0 : 1;

        $formatter = new ByteSize\Formatter\Binary();
        $formatter->setPrecision($precision);

        return $formatter->format($bytes);
    }
669123
public static function getRandomBytes($byteLength)
    {
        $results = null;

        if (function_exists('openssl_random_pseudo_bytes')) {
            /** @noinspection CryptographicallySecureRandomnessInspection */
            $results = openssl_random_pseudo_bytes($byteLength);
        } elseif (is_readable('/dev/urandom')) {
            $fileHandler = fopen('/dev/urandom', 'rb');

            if ($fileHandler !== false) {
                $results = fread($fileHandler, $byteLength);

                fclose($fileHandler);
            }
        } elseif (function_exists('mcrypt_create_iv')
                  && version_compare(PHP_VERSION, '5.3.0', '>=')
        ) {
            /** @noinspection CryptographicallySecureRandomnessInspection */
            /** @noinspection PhpDeprecationInspection */
            $results = mcrypt_create_iv($byteLength, MCRYPT_DEV_RANDOM);
        } elseif (function_exists('random_bytes')) {
            $results = random_bytes($byteLength);
        } elseif (class_exists('COM')) {
            /** @noinspection BadExceptionsProcessingInspection */
            try {
                /** @noinspection PhpUndefinedClassInspection */
                /** @noinspection SpellCheckingInspection */
                $capiUtil = new \COM('CAPICOM.Utilities.1');
                /** @noinspection PhpUndefinedMethodInspection */
                /** @noinspection SpellCheckingInspection */
                $results = $capiUtil->GetRandom($byteLength, 0);
            } catch (\Exception $ex) {
            } // Fail silently
        }

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($results)) {
            throw new Exception\RuntimeException(
                'Unable to find a secure method for generating random bytes.'
            );
        }

        return $results;
    }
377230
public function generateSessionKey()
    {
        if (!isset($this->cryptParams['keysize'])) {
            throw new Exception('Unknown key size for type "' . $this->type . '".');
        }
        $keysize = $this->cryptParams['keysize'];

        $key = openssl_random_pseudo_bytes($keysize);

        if ($this->type === self::TRIPLEDES_CBC) {
            /* Make sure that the generated key has the proper parity bits set.
             * Mcrypt doesn't care about the parity bits, but others may care.
            */
            for ($i = 0; $i < strlen($key); $i++) {
                $byte = ord($key[$i]) & 0xfe;
                $parity = 1;
                for ($j = 1; $j < 8; $j++) {
                    $parity ^= ($byte >> $j) & 1;
                }
                $byte |= $parity;
                $key[$i] = chr($byte);
            }
        }

        $this->key = $key;
        return $key;
    }
1237335
public function getRandomBytesString($byteCount){
        $chars = '';
        // try mcrypt
        if ($this->mcrypt) {
            $chars = mcrypt_create_iv($byteCount, MCRYPT_DEV_URANDOM);
        }
        // if it fails, use openssl_random_pseudo_bytes
        if (!$chars && $this->openssl) {
            $chars = openssl_random_pseudo_bytes($byteCount);
        }
        // if it fails, try /dev/urandom (will work only on unix based systems)
        if (!$chars && $this->urandom) {
            while (($len  = strlen($chars))< $byteCount) {
                $chars .= fread($this->urandomFileHandler, $byteCount - $len);
            }
        }
        // if it fails, throw an Exception
        if ($len = strlen($chars) < $byteCount) {
            throw new Exception('Cannot use a cryptographically secure PRNG.');
        }
        return $chars;
    }
525944
private function generarId()
    {
        if (function_exists('random_bytes')) {
            $semilla = random_bytes(32);
        } elseif (function_exists('mcrypt_create_iv')) {
            $semilla = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
            $semilla = openssl_random_pseudo_bytes(32);
        } else {
            $semilla = uniqid('armazon', true);
        }

        return hash('sha256', $semilla);
    }
884341
protected function getReadableBytes($bytes, $precision)
    {
        $suffix = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
        $total = count($suffix);

        for ($i = 0; $bytes > 1024 && $i < $total; $i++) {
            $bytes /= 1024;
        }

        return number_format($bytes, $precision) . ' ' . $suffix[$i];
    }