Radcli library 2.0.0
A simple radius library -- legacy API reference
Loading...
Searching...
No Matches
rc-random.c
1/*
2 * Copyright (C) 2026 Nikos Mavrogiannopoulos
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 */
24
25/* This is the single place that dispatches to gnutls_rnd()/getentropy();
26 * every Request Authenticator and packet-ID generator in the library goes
27 * through it instead of duplicating the #if defined(HAVE_GNUTLS) branch.
28 * See REQ-GEN-SEC-007 in doc/requirements/general.md. */
29
30#include <config.h>
31#include "rc-random.h"
32
33#include <assert.h>
34
35#if defined(HAVE_GNUTLS)
36# include <gnutls/gnutls.h>
37# include <gnutls/crypto.h>
38#endif
39
40/*- Fill a buffer with cryptographically random bytes, via gnutls_rnd() or
41 * getentropy().
42 *
43 * @param buf the buffer to fill.
44 * @param len the number of random bytes to write into buf.
45 -*/
46void rc_get_random_bytes(void *buf, size_t len)
47{
48#if defined(HAVE_GNUTLS)
49 int ret = gnutls_rnd(GNUTLS_RND_NONCE, buf, len);
50 assert(ret >= 0);
51#else
52 int ret = getentropy(buf, len);
53 assert(ret == 0);
54#endif
55}
56
57/*- Return a single cryptographically random byte.
58 -*/
59unsigned char rc_get_random_byte(void)
60{
61 unsigned char b;
62 rc_get_random_bytes(&b, 1);
63 return b;
64}