lithium\security\Random::generate()

public static method

Generates random bytes for use in UUIDs and password salts, using a cryptographically strong random number generator source.

$bits = Random::generate(8); // 64 bits
$hex = bin2hex($bits); // [0-9a-f]+

Optionally base64-encodes the resulting random string per the following. The alphabet used by base64_encode() is different than the one we should be using. When considering the meaty part of the resulting string, however, a bijection allows to go the from one to another. Given that we're working on random bytes, we can use safely use base64_encode() without losing any entropy.

Parameters

  • integer $bytes

    The number of random bytes to generate.

  • array $options

    The options used when generating random bytes:

    • 'encode' integer: If specified, and set to Random::ENCODE_BASE_64, the resulting value will be base64-encoded, per the note above.

Returns

string

Returns (an encoded) string of random bytes.

Source

	public static function generate($bytes, array $options = []) {
		$defaults = ['encode' => null];
		$options += $defaults;

		$source = static::$_source ?: (static::$_source = static::_source());
		$result = $source($bytes);

		if ($options['encode'] !== static::ENCODE_BASE_64) {
			return $result;
		}
		return strtr(rtrim(base64_encode($result), '='), '+', '.');
	}