1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
6 * The library is free for all purposes without any express
11 #if defined(LTC_MDSA) || defined(LTC_MECC)
13 Generate a random number N with given bitlength (note: MSB can be 0)
16 int rand_bn_bits(void *N, int bits, prng_state *prng, int wprng)
19 unsigned char *buf, mask;
21 LTC_ARGCHK(N != NULL);
25 if ((res = prng_is_valid(wprng)) != CRYPT_OK) return res;
27 bytes = (bits+7) >> 3;
28 mask = 0xff << (8 - bits % 8);
31 if ((buf = XCALLOC(1, bytes)) == NULL) return CRYPT_MEM;
33 /* generate random bytes */
34 if (prng_descriptor[wprng].read(buf, bytes, prng) != (unsigned long)bytes) {
35 res = CRYPT_ERROR_READPRNG;
41 if ((res = mp_read_unsigned_bin(N, buf, bytes)) != CRYPT_OK) goto cleanup;
46 #ifdef LTC_CLEAN_STACK
54 Generate a random number N in a range: 1 <= N < limit
56 int rand_bn_upto(void *N, void *limit, prng_state *prng, int wprng)
60 LTC_ARGCHK(N != NULL);
61 LTC_ARGCHK(limit != NULL);
63 bits = mp_count_bits(limit);
65 res = rand_bn_bits(N, bits, prng, wprng);
66 if (res != CRYPT_OK) return res;
67 } while (mp_cmp_d(N, 0) != LTC_MP_GT || mp_cmp(N, limit) != LTC_MP_LT);
73 /* ref: $Format:%D$ */
74 /* git commit: $Format:%H$ */
75 /* commit time: $Format:%ai$ */