1 // SPDX-License-Identifier: BSD-2-Clause
2 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 *
4 * LibTomCrypt is a library that provides various cryptographic
5 * algorithms in a highly modular and flexible manner.
6 *
7 * The library is free for all purposes without any express
8 * guarantee it works.
9 */
10 #include "tomcrypt_private.h"
11
12 #ifdef LTC_RNG_MAKE_PRNG
13 /**
14 @file rng_make_prng.c
15 portable way to get secure random bits to feed a PRNG (Tom St Denis)
16 */
17
18 /**
19 Create a PRNG from a RNG
20
21 In case you pass bits as '-1' the PRNG will be setup
22 as if the export/import functionality has been used,
23 but the imported data comes directly from the RNG.
24
25 @param bits Number of bits of entropy desired (-1 or 64 ... 1024)
26 @param wprng Index of which PRNG to setup
27 @param prng [out] PRNG state to initialize
28 @param callback A pointer to a void function for when the RNG is slow, this can be NULL
29 @return CRYPT_OK if successful
30 */
rng_make_prng(int bits,int wprng,prng_state * prng,void (* callback)(void))31 int rng_make_prng(int bits, int wprng, prng_state *prng,
32 void (*callback)(void))
33 {
34 unsigned char* buf;
35 unsigned long bytes;
36 int err;
37
38 LTC_ARGCHK(prng != NULL);
39
40 /* check parameter */
41 if ((err = prng_is_valid(wprng)) != CRYPT_OK) {
42 return err;
43 }
44
45 if (bits == -1) {
46 bytes = prng_descriptor[wprng]->export_size;
47 } else if (bits < 64 || bits > 1024) {
48 return CRYPT_INVALID_PRNGSIZE;
49 } else {
50 bytes = (unsigned long)((bits+7)/8) * 2;
51 }
52
53 if ((err = prng_descriptor[wprng]->start(prng)) != CRYPT_OK) {
54 return err;
55 }
56
57 buf = XMALLOC(bytes);
58 if (buf == NULL) {
59 return CRYPT_MEM;
60 }
61
62 if (rng_get_bytes(buf, bytes, callback) != bytes) {
63 err = CRYPT_ERROR_READPRNG;
64 goto LBL_ERR;
65 }
66
67 if (bits == -1) {
68 if ((err = prng_descriptor[wprng]->pimport(buf, bytes, prng)) != CRYPT_OK) {
69 goto LBL_ERR;
70 }
71 } else {
72 if ((err = prng_descriptor[wprng]->add_entropy(buf, bytes, prng)) != CRYPT_OK) {
73 goto LBL_ERR;
74 }
75 }
76 if ((err = prng_descriptor[wprng]->ready(prng)) != CRYPT_OK) {
77 goto LBL_ERR;
78 }
79
80 LBL_ERR:
81 #ifdef LTC_CLEAN_STACK
82 zeromem(buf, bytes);
83 #endif
84 XFREE(buf);
85 return err;
86 }
87 #endif /* #ifdef LTC_RNG_MAKE_PRNG */
88
89
90 /* ref: $Format:%D$ */
91 /* git commit: $Format:%H$ */
92 /* commit time: $Format:%ai$ */
93