a5809aa2bc952e7a80908b4d140350d0febd4844
[samba.git] / lib / util / genrand.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Functions to create reasonable random numbers for crypto use.
5
6    Copyright (C) Jeremy Allison 2001
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "replace.h"
23 #include "lib/util/genrand.h"
24
25 #include <gnutls/gnutls.h>
26 #include <gnutls/crypto.h>
27
28 /*
29  * Details about the GnuTLS CSPRNG:
30  *
31  * https://nikmav.blogspot.com/2017/03/improving-by-simplifying-gnutls-prng.html
32  */
33
34 _PUBLIC_ void generate_random_buffer(uint8_t *out, int len)
35 {
36         /* Thread and fork safe random number generator for temporary keys. */
37         gnutls_rnd(GNUTLS_RND_RANDOM, out, len);
38 }
39
40 _PUBLIC_ void generate_secret_buffer(uint8_t *out, int len)
41 {
42         /* The key generator, will re-seed after a fixed amount of bytes is
43          * generated (typically less than the nonce), and will also re-seed
44          * based on time, i.e., after few hours of operation without reaching
45          * the limit for a re-seed. For its re-seed it mixes mixes data obtained
46          * from the OS random device with the previous key.
47          */
48         gnutls_rnd(GNUTLS_RND_KEY, out, len);
49 }
50
51 _PUBLIC_ void generate_nonce_buffer(uint8_t *out, int len)
52 {
53         /*
54          * The nonce generator will reseed after outputting a fixed amount of
55          * bytes (typically few megabytes), or after few hours of operation
56          * without reaching the limit has passed.
57          */
58         gnutls_rnd(GNUTLS_RND_NONCE, out, len);
59 }