/* * Ouroboros - Copyright (C) 2016 - 2026 * * Pseudo random generator * * Dimitri Staessens * Sander Vrijders * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., http://www.fsf.org/about/contact/. */ #include "config.h" #include #if defined(__APPLE__) || defined(__FreeBSD__) #include #elif defined(HAVE_SYS_RANDOM) #include #include #include #elif defined(HAVE_LIBGCRYPT) #include #elif defined(HAVE_OPENSSL_RNG) #include #include #endif int random_buffer(void * buf, size_t len) { #if defined(__APPLE__) || defined(__FreeBSD__) arc4random_buf(buf, len); return 0; #elif defined(HAVE_SYS_RANDOM) size_t off = 0; ssize_t ret; while (off < len) { ret = getrandom((uint8_t *) buf + off, len - off, GRND_NONBLOCK); if (ret < 0) { if (errno == EINTR) continue; return -1; } off += (size_t) ret; } return 0; #elif defined(HAVE_LIBGCRYPT) gcry_randomize(buf, len, GCRY_STRONG_RANDOM); return 0; #elif defined(HAVE_OPENSSL_RNG) if (len == 0 || len >= INT_MAX) return -1; return RAND_bytes((unsigned char *) buf, (int) len) == 1 ? 0 : -1; #endif }