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 #if defined(LTC_MDSA) || defined(LTC_MECC)
13 /**
14   Generate a random number N with given bitlength (note: MSB can be 0)
15 */
16 
rand_bn_bits(void * N,int bits,prng_state * prng,int wprng)17 int rand_bn_bits(void *N, int bits, prng_state *prng, int wprng)
18 {
19    int res, bytes;
20    unsigned char *buf, mask;
21 
22    LTC_ARGCHK(N != NULL);
23    LTC_ARGCHK(bits > 1);
24 
25    /* check PRNG */
26    if ((res = prng_is_valid(wprng)) != CRYPT_OK) return res;
27 
28    bytes = (bits+7) >> 3;
29    mask = 0xff << (8 - bits % 8);
30 
31    /* allocate buffer */
32    if ((buf = XCALLOC(1, bytes)) == NULL) return CRYPT_MEM;
33 
34    /* generate random bytes */
35    if (prng_descriptor[wprng]->read(buf, bytes, prng) != (unsigned long)bytes) {
36       res = CRYPT_ERROR_READPRNG;
37       goto cleanup;
38    }
39    /* mask bits */
40    buf[0] &= ~mask;
41    /* load value */
42    if ((res = mp_read_unsigned_bin(N, buf, bytes)) != CRYPT_OK) goto cleanup;
43 
44    res = CRYPT_OK;
45 
46 cleanup:
47 #ifdef LTC_CLEAN_STACK
48    zeromem(buf, bytes);
49 #endif
50    XFREE(buf);
51    return res;
52 }
53 
54 /**
55   Generate a random number N in a range: 1 <= N < limit
56 */
rand_bn_upto(void * N,void * limit,prng_state * prng,int wprng)57 int rand_bn_upto(void *N, void *limit, prng_state *prng, int wprng)
58 {
59    int res, bits;
60 
61    LTC_ARGCHK(N != NULL);
62    LTC_ARGCHK(limit != NULL);
63 
64    bits = mp_count_bits(limit);
65    do {
66      res = rand_bn_bits(N, bits, prng, wprng);
67      if (res != CRYPT_OK) return res;
68    } while (mp_cmp_d(N, 0) != LTC_MP_GT || mp_cmp(N, limit) != LTC_MP_LT);
69 
70    return CRYPT_OK;
71 }
72 #endif
73 
74 /* ref:         $Format:%D$ */
75 /* git commit:  $Format:%H$ */
76 /* commit time: $Format:%ai$ */
77