Generate pseudorandom bytes.

@param integer $len
@return binary
349177
public function bytes($len) {
    /* Code inspired by this blogpost by Enrico Zimuel
     * http://www.zimuel.it/en/strong-cryptography-in-php/ */
    $strong = false;
    if(function_exists('openssl_random_pseudo_bytes')) {
      $rnd = openssl_random_pseudo_bytes($len, $strong);
      if($strong === true) {
        return $rnd;
      }
    }

    /* Either we dont have the OpenSSL library or the data returned was not
     * considered secure. Fall back on this less secure code. */
    if(function_exists('mcrypt_create_iv')) {
      $rnd = mcrypt_create_iv($len, MCRYPT_DEV_URANDOM);
      return $rnd;
    }

    /* Either we dont have the MCrypt library and OpenSSL library or the data returned was not
     * considered secure. Fall back on this less secure code. */
    $rnd = '';
    for ($i=0;$i<$len;$i++) {
      $sha = hash('sha256', mt_rand());
      $char = mt_rand(0,30);
      $rnd .= chr(hexdec($sha[$char].$sha[$char+1]));
    }
    return (binary) $rnd;
  }
333928
public static function fromKeyLength(int $len): self
    {
        $bits = $len << 3;
        if (!array_key_exists($bits, self::MAP_KEYSIZE_TO_CLS)) {
            throw new \UnexpectedValueException(
                "No AES implementation for $bits-bit key size.");
        }
        $cls = self::MAP_KEYSIZE_TO_CLS[$bits];
        return new $cls();
    }
176066
public static String randomString(int len, Random random) {
        if (len < 1) {
            return "";
        }
        int start = ' ';
        int end = 'z' + 1;

        StringBuffer buffer = new StringBuffer();
        int gap = end - start;

        while (len-- != 0) {
            char ch;
            ch = (char) (random.nextInt(gap) + start);

            if (Character.isLetterOrDigit(ch)) {
                buffer.append(ch);
            } else {
                len++;
            }
        }
        return buffer.toString();
    }
1184451
public static function generateRandomHandle($length = 32)
    {
        do {
            $handle = substr(md5(mt_rand(0, mt_getrandmax())), 0, $length);
        } while (static::getByField(static::$handleField, $handle));

        return $handle;
    }
210464
public function generatePseudoRandomBlock()
	{
		$bytes='';

		if (function_exists('openssl_random_pseudo_bytes')
			&& ($bytes=openssl_random_pseudo_bytes(512))!==false
			&& $this->strlen($bytes)>=512)
		{
			return $this->substr($bytes,0,512);
		}

		for($i=0;$i<32;++$i)
			$bytes.=pack('S',mt_rand(0,0xffff));

		// On UNIX and UNIX-like operating systems the numerical values in `ps`, `uptime` and `iostat`
		// ought to be fairly unpredictable. Gather the non-zero digits from those.
		foreach(array('ps','uptime','iostat') as $command) {
			@exec($command,$commandResult,$retVal);
			if(is_array($commandResult) && !empty($commandResult) && $retVal==0)
				$bytes.=preg_replace('/[^1-9]/','',implode('',$commandResult));
		}

		// Gather the current time's microsecond part. Note: this is only a source of entropy on
		// the first call! If multiple calls are made, the entropy is only as much as the
		// randomness in the time between calls.
		$bytes.=$this->substr(microtime(),2,6);

		// Concatenate everything gathered, mix it with sha512. hash() is part of PHP core and
		// enabled by default but it can be disabled at compile time but we ignore that possibility here.
		return hash('sha512',$bytes,true);
	}
1064953
function generateRandomBytes (size, attempts, callback) {
  crypto.randomBytes(size, function onRandomBytes (err, buf) {
    if (!err) return callback(null, buf)
    if (!--attempts) return callback(err)
    setTimeout(generateRandomBytes.bind(null, size, attempts, callback), 10)
  })
}
824599
public static function random($type = 'alnum', $length = 8)
    {
        switch ($type) {
            case 'alnum':
            case 'numeric':
            case 'nozero':
                $pool = self::getPoolForRandom($type);

                return static::randomFrom($pool, $length);
            case 'unique':
                return md5(uniqid(mt_rand(), true));
            case 'guid':
                return self::generateGUID();
            default:
                throw new \InvalidArgumentException('unknown random type');
        }
    }
613399
protected static function getRandomBytes($length)
    {
        if (is_readable('/dev/urandom')) {
            $handle = fopen('/dev/urandom', 'rb');
            $read = fread($handle, $length);
            fclose($handle);
            return $read;
        }
        if (function_exists('random_bytes')) {
            return random_bytes($length);
        }
        if (function_exists('mcrypt_create_iv')) {
            return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
        }
		return pack('I', mt_rand(0, mt_getrandmax()));
	}
151893
public function readAll($len)
    {
        // return $this->read($len);

        $data = '';
        $got = 0;
        while (($got = TStringFuncFactory::create()->strlen($data)) < $len) {
            $data .= $this->read($len - $got);
        }

        return $data;
    }
608699
public static function generateUniqueRandomAlphaNumericString($length){
        if(!function_exists('openssl_random_pseudo_bytes'))
            throw new Exception("openssl_random_pseudo_bytes is not defined!");

        if($length % 2 == 0)
            return bin2hex(openssl_random_pseudo_bytes($length));

        return substr(bin2hex(openssl_random_pseudo_bytes($length + 1)), 0, -1);
    }
716282
public static function randomHex(int $length = 128): string
    {
        $bytes = ceil($length / 2);
        $hex = bin2hex(self::randomBytes($bytes));
        return $hex;
    }
1010447
public static function genRandomStr($l) {
		$p = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$s = '';
		for ($i = 0; $i < $l; $i++) {
			$s .= $p[mt_rand(0, (mb_strlen($p) - 1))];
		}
		return $s;
	}
129506
public function getByte($length)
    {
        if ($length === 0) {
            return '';
        }

        if (function_exists('random_bytes')) {
            /** @noinspection PhpUnhandledExceptionInspection */
            return random_bytes($length);
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
            /** @noinspection CryptographicallySecureRandomnessInspection */
            return openssl_random_pseudo_bytes($length);
        } elseif (file_exists('/dev/urandom')) {
            $handle = fopen('/dev/urandom', 'rb');

            stream_set_read_buffer($handle, 0);
            $r = fread($handle, $length);
            fclose($handle);

            return $r;
        } else {
            $r = '';

            do {
                $r .= pack('L', mt_rand());
            } while (strlen($r) < $length);

            return substr($r, 0, $length);
        }
    }
772823
public static function random_bytes($length, $raw = false)
    {
        $hextab  = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $tabsize = strlen($hextab);

        // Use PHP7 true random generator
        if ($raw && function_exists('random_bytes')) {
            return random_bytes($length);
        }

        if (!$raw && function_exists('random_int')) {
            $result = '';
            while ($length-- > 0) {
                $result .= $hextab[random_int(0, $tabsize - 1)];
            }

            return $result;
        }

        $random = openssl_random_pseudo_bytes($length);

        if ($random === false && $length > 0) {
            throw new Exception("Failed to get random bytes");
        }

        if (!$raw) {
            for ($x = 0; $x < $length; $x++) {
                $random[$x] = $hextab[ord($random[$x]) % $tabsize];
            }
        }

        return $random;
    }
865333
public static function flags2bitarray($flags, $len = 4)
    {
        $ret = 0;
        foreach ($flags as $v) {
            $ret |= $v;
        }
        return static::i2b($len, $ret);
    }
706200
public function getRandomString($length = 42)
	{
		// We'll check if the user has OpenSSL installed with PHP. If they do
		// we'll use a better method of getting a random string. Otherwise, we'll
		// fallback to a reasonably reliable method.
		if (function_exists('openssl_random_pseudo_bytes'))
		{
			// We generate twice as many bytes here because we want to ensure we have
			// enough after we base64 encode it to get the length we need because we
			// take out the "/", "+", and "=" characters.
			$bytes = openssl_random_pseudo_bytes($length * 2);

			// We want to stop execution if the key fails because, well, that is bad.
			if ($bytes === false)
			{
				throw new \RuntimeException('Unable to generate random string.');
			}

			return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length);
		}

		$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

		return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
	}
686838
private static function generateSalt (int $length) : string
	{
		// Not 100% unique, not 100% random, but good enough for a salt
		// MD5 returns 32 characters
		$uniqueRandomString = md5(uniqid(mt_rand(),true));

		// Valid Characters for a salt are [a-AZ-Z0-9./]
		$base64String = base64_encode($uniqueRandomString);

		// But no '+' which is valid in base64 encoding
		$modifiedBase64String = str_replace('+', '.', $base64String);

		// Truncate String to the correct length
		return substr($modifiedBase64String, 0, $length);
	}