2 * Crypto-quality random number functions
4 * Author: Harlan Stenn, 2014
6 * This file is Copyright (c) 2014 by Network Time Foundation.
7 * BSD terms apply: see the file COPYRIGHT in the distribution root for details.
11 #include <sys/types.h>
18 #include <ntp_random.h>
20 #ifdef USE_OPENSSL_CRYPTO_RAND
21 #include <openssl/err.h>
22 #include <openssl/rand.h>
24 int crypto_rand_init = 0;
27 # ifndef HAVE_ARC4RANDOM_BUF
29 arc4random_buf(void *buf, size_t nbytes);
32 evutil_secure_rng_get_bytes(void *buf, size_t nbytes);
35 arc4random_buf(void *buf, size_t nbytes)
37 evutil_secure_rng_get_bytes(buf, nbytes);
44 * As of late 2014, here's how we plan to provide cryptographic-quality
47 * - If we are building with OpenSSL, use RAND_poll() and RAND_bytes().
48 * - Otherwise, use arc4random().
50 * Use of arc4random() can be forced using configure --disable-openssl-random
52 * We can count on arc4random existing, thru the OS or thru libevent.
53 * The quality of arc4random depends on the implementor.
55 * RAND_poll() doesn't show up until XXX. If it's not present, we
56 * need to either provide our own or use arc4random().
62 * Initialize the random number generator, if needed by the underlying
63 * crypto random number generation mechanism.
71 #ifdef USE_OPENSSL_CRYPTO_RAND
72 if (!crypto_rand_init) {
77 /* No initialization needed for arc4random() */
83 * ntp_crypto_random_buf:
85 * Returns 0 on success, -1 on error.
88 ntp_crypto_random_buf(
93 #ifdef USE_OPENSSL_CRYPTO_RAND
96 rc = RAND_bytes(buf, nbytes);
101 err = ERR_get_error();
102 err_str = ERR_error_string(err, NULL);
103 /* XXX: Log the error */
110 arc4random_buf(buf, nbytes);