Excerpt this article:
Sodium (and NaCl) is an “opinionated” library: this means the algorithms used have been selected and cannot be changed. The library uses some of the most robust algorithms available, including Elliptic-curve cryptography (ECC).
And random_bytes() is not used to encrypt messages, this function only generates random bytecodes.
This sample code is to generate keys using Sodium:
$msg = 'This is a super secret message!';
// Generating an encryption key and a nonce
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES); // 256 bit
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // 24 bytes
// Encrypt
$ciphertext = sodium_crypto_secretbox($msg, $nonce, $key);
// Decrypt
$plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
echo $plaintext === $msg ? 'Success' : 'Error';
See? SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
is actually a predefined constant, which is the length of the key. Follow this document for other predefined constants.