Draws n bytes from the operating system's cryptographic random source:
rand_s on Windows, arc4random_buf on macOS and the BSDs, getrandom on
Linux with glibc 2.25 or later, and /dev/urandom elsewhere. Where the
kernel or a seccomp filter refuses getrandom (a kernel before 3.17), it
reads /dev/urandom instead. crypt_info() names the source in use, in
build_flags$random_backend. Use these bytes for keys, initialisation
vectors, nonces and salts.
Details
R's random number generator is never involved. set.seed() has no
effect on these bytes and they do not change .Random.seed, so drawing
them does not disturb a reproducible simulation running beside them. That
is deliberate: R's generator is seeded from the session and reproducible on
purpose, which is exactly what a key must not be.
The name, argument and default mirror openssl::rand_bytes(), so code
moving from openssl changes only the prefix.
Errors
A failure of the operating-system source raises an error of class
zucrypt_entropy_error. It never returns fewer bytes than asked for, and
never returns bytes from a source that reported failure. An invalid n is
zucrypt_invalid_argument.
See also
crypt_aes_cbc_encrypt_nopad(), whose iv for encryption must be
unpredictable: crypt_rand_bytes(16) is one.
Examples
crypt_rand_bytes(16)
#> [1] ea 45 56 5a a4 07 05 05 bf 25 18 8b b8 df 37 0d
# A 256-bit key, printed as hex.
crypt_hex(crypt_rand_bytes(32))
#> [1] "2fc8c1faf451368c53024f0da9b8ba74adfad8f7839a3bffb2a3f474367cf12e"
# set.seed() does not repeat it.
set.seed(1)
a <- crypt_rand_bytes(8)
set.seed(1)
b <- crypt_rand_bytes(8)
identical(a, b)
#> [1] FALSE