Skip to content

Core\Random::bytes

Draws the number of random bytes you ask for, for a key, a salt or a nonce.

The bytes come from a cryptographic random generator, so nobody can guess the next value from the values before it. The result is a bytes value of exactly the length you asked for. It is raw data and not text, so you convert it with Core\Encoding::toHex or Core\Encoding::toBase64 before you store it or show it.

Asking for zero bytes throws an error. An empty key is equal to every other empty key, so it protects nothing.

Good to know: when you want random text for a link or a session, Core\Random::token returns it as hex in one call.

Parameters

  • $countuintHow many bytes to return. It must be at least 1.

Return value

Returns bytes. A bytes value with exactly $count raw bytes. For random bytes as a hex string, use Core\Random::token.

Errors

  • RuntimeError$count is 0, or it is larger than a buffer this process can allocate.

Examples

Draw a key

<?nvs
// Shows how to draw a random key of 32 bytes and write it as hex.
bytes $key = Core\Random::bytes(32);
// The key has exactly the length you asked for. This prints 32.
echo Core\Bytes::length($key), "\n";
// `Core\Encoding::toHex` writes each byte as two characters. This prints 64.
string $hex = Core\Encoding::toHex($key);
echo Core\Str::length($hex), "\n";
Output
32
64

Zero bytes is an error

<?nvs
// Shows what happens when a program asks for zero bytes.
// The count here comes from a calculation that went wrong.
uint $count = 0;
// `Core\Random::bytes(0)` throws an error. An empty key would protect nothing.
try {
bytes $key = Core\Random::bytes($count);
echo Core\Bytes::length($key), "\n";
} catch (Throwable $e) {
echo 'Error: ', $e->message, "\n";
}
Output
Error: Core\Random::bytes(): a draw of zero bytes is the empty buffer, which is not a secret — draw at least one byte

A nonce for each page

<?nvs
// Shows how to make a new nonce for every page, for a Content-Security-Policy header.
// 16 random bytes in Base64 give a text of 24 characters.
string $nonce = Core\Encoding::toBase64(Core\Random::bytes(16));
string $policy = "script-src 'nonce-" . $nonce . "'";
// The nonce is different on every run, so this prints only its length: 24.
echo Core\Str::length($nonce), "\n";
// The same nonce goes into the header and into each script tag on the page.
string $tag = '<script nonce="' . $nonce . '">start();</script>';
echo Core\Str::contains($policy, $nonce) && Core\Str::contains($tag, $nonce) ? 'match' : 'no match', "\n";
Output
24
match