1 /*
2 * coap_prng.h -- Pseudo Random Numbers
3 *
4 * Copyright (C) 2010-2023 Olaf Bergmann <bergmann@tzi.org>
5 *
6 * SPDX-License-Identifier: BSD-2-Clause
7 *
8 * This file is part of the CoAP library libcoap. Please see README for terms
9 * of use.
10 */
11
12 /**
13 * @file coap_prng.h
14 * @brief Pseudo Random Numbers
15 */
16
17 #ifndef COAP_PRNG_H_
18 #define COAP_PRNG_H_
19
20 /**
21 * @ingroup application_api
22 * @defgroup coap_prng Pseudo Random Numbers
23 * API for generating pseudo random numbers
24 * @{
25 */
26
27 #if defined(WITH_LWIP) && defined(LWIP_RAND)
28
29 COAP_STATIC_INLINE int
lwip_prng_impl(unsigned char * buf,size_t len)30 lwip_prng_impl(unsigned char *buf, size_t len) {
31 u32_t v = LWIP_RAND();
32 while (len > sizeof(v)) {
33 memcpy(buf, &v, sizeof(v));
34 len -= sizeof(v);
35 buf += sizeof(v);
36 v = LWIP_RAND();
37 }
38
39 memcpy(buf, &v, len);
40 return 1;
41 }
42
43 #define coap_prng(Buf,Length) lwip_prng_impl((Buf), (Length))
44 #define coap_prng_init(Value) (void)Value
45
46 #else
47
48 /**
49 * Data type for random number generator function. The function must
50 * fill @p len bytes of random data into the buffer starting at @p
51 * out. On success, the function should return 1, zero otherwise.
52 */
53 typedef int (*coap_rand_func_t)(void *out, size_t len);
54
55 /**
56 * Replaces the current random number generation function with the
57 * default function @p rng.
58 *
59 * @param rng The random number generation function to use.
60 */
61 void coap_set_prng(coap_rand_func_t rng);
62
63 /**
64 * Seeds the default random number generation function with the given
65 * @p seed. The default random number generation function will use
66 * getrandom() if available, ignoring the seed.
67 *
68 * @param seed The seed for the pseudo random number generator.
69 */
70 void coap_prng_init(unsigned int seed);
71
72 /**
73 * Fills @p buf with @p len random bytes using the default pseudo
74 * random number generator. The default PRNG can be changed with
75 * coap_set_prng(). This function returns 1 when @p len random bytes
76 * have been written to @p buf, zero otherwise.
77 *
78 * @param buf The buffer to fill with random bytes.
79 * @param len The number of random bytes to write into @p buf.
80 *
81 * @return 1 on success, 0 otherwise.
82 */
83 int coap_prng(void *buf, size_t len);
84
85 #endif /* POSIX */
86
87 /** @} */
88
89 #endif /* COAP_PRNG_H_ */
90