this set of functions generates random bytes or numbers from OpenSSL. This
provides a cryptographically secure alternative to R's default random number generator.
rand_bytes generates n random cryptographically secure bytes
References
OpenSSL manual: https://docs.openssl.org/1.1.1/man3/RAND_bytes/
Examples
rnd <- rand_bytes(10)
as.numeric(rnd)
#> [1] 120 176 85 201 35 20 231 226 71 134
as.character(rnd)
#> [1] "78" "b0" "55" "c9" "23" "14" "e7" "e2" "47" "86"
as.logical(rawToBits(rnd))
#> [1] FALSE FALSE FALSE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE
#> [13] TRUE TRUE FALSE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE FALSE
#> [25] TRUE FALSE FALSE TRUE FALSE FALSE TRUE TRUE TRUE TRUE FALSE FALSE
#> [37] FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE
#> [49] TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE FALSE TRUE FALSE FALSE
#> [61] FALSE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE
#> [73] FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE
# bytes range from 0 to 255
rnd <- rand_bytes(100000)
hist(as.numeric(rnd), breaks=-1:255)
# Generate random doubles between 0 and 1
rand_num(5)
#> [1] 0.6532462 0.9887103 0.5164745 0.7013525 0.1122981
# Use CDF to map [0,1] into random draws from a distribution
x <- qnorm(rand_num(1000), mean=100, sd=15)
hist(x)
y <- qbinom(rand_num(1000), size=10, prob=0.3)
hist(y)