comparison libtomcrypt/src/math/rand_bn.c @ 1471:6dba84798cd5

Update to libtomcrypt 1.18.1, merged with Dropbear changes
author Matt Johnston <matt@ucc.asn.au>
date Fri, 09 Feb 2018 21:44:05 +0800
parents
children e9dba7abd939
comparison
equal deleted inserted replaced
1470:8bba51a55704 1471:6dba84798cd5
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
2 *
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
5 *
6 * The library is free for all purposes without any express
7 * guarantee it works.
8 */
9 #include "tomcrypt.h"
10
11 #ifdef LTC_MDSA
12 /**
13 Generate a random number N with given bitlength (note: MSB can be 0)
14 */
15
16 int rand_bn_bits(void *N, int bits, prng_state *prng, int wprng)
17 {
18 int res, bytes;
19 unsigned char *buf, mask;
20
21 LTC_ARGCHK(N != NULL);
22 LTC_ARGCHK(bits > 1);
23
24 /* check PRNG */
25 if ((res = prng_is_valid(wprng)) != CRYPT_OK) return res;
26
27 bytes = (bits+7) >> 3;
28 mask = 0xff << (8 - bits % 8);
29
30 /* allocate buffer */
31 if ((buf = XCALLOC(1, bytes)) == NULL) return CRYPT_MEM;
32
33 /* generate random bytes */
34 if (prng_descriptor[wprng].read(buf, bytes, prng) != (unsigned long)bytes) {
35 res = CRYPT_ERROR_READPRNG;
36 goto cleanup;
37 }
38 /* mask bits */
39 buf[0] &= ~mask;
40 /* load value */
41 if ((res = mp_read_unsigned_bin(N, buf, bytes)) != CRYPT_OK) goto cleanup;
42
43 res = CRYPT_OK;
44
45 cleanup:
46 #ifdef LTC_CLEAN_STACK
47 zeromem(buf, bytes);
48 #endif
49 XFREE(buf);
50 return res;
51 }
52
53 /**
54 Generate a random number N in a range: 1 <= N < limit
55 */
56 int rand_bn_upto(void *N, void *limit, prng_state *prng, int wprng)
57 {
58 int res, bits;
59
60 LTC_ARGCHK(N != NULL);
61 LTC_ARGCHK(limit != NULL);
62
63 bits = mp_count_bits(limit);
64 do {
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);
68
69 return CRYPT_OK;
70 }
71 #endif
72
73 /* ref: $Format:%D$ */
74 /* git commit: $Format:%H$ */
75 /* commit time: $Format:%ai$ */