2018-05-02 19:43:17 +00:00
|
|
|
#include "tommath_private.h"
|
2004-10-29 22:07:18 +00:00
|
|
|
#ifdef BN_MP_RAND_C
|
2019-04-07 13:29:11 +00:00
|
|
|
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
|
|
|
|
/* SPDX-License-Identifier: Unlicense */
|
2003-02-28 16:08:34 +00:00
|
|
|
|
2019-05-12 22:22:18 +00:00
|
|
|
mp_err(*s_mp_rand_source)(void *out, size_t size) = s_mp_rand_platform;
|
2019-05-07 10:26:46 +00:00
|
|
|
|
2019-05-12 22:22:18 +00:00
|
|
|
void mp_rand_source(mp_err(*source)(void *out, size_t size))
|
2019-05-07 10:26:46 +00:00
|
|
|
{
|
2019-05-12 09:33:17 +00:00
|
|
|
s_mp_rand_source = (source == NULL) ? s_mp_rand_platform : source;
|
2019-05-07 10:26:46 +00:00
|
|
|
}
|
|
|
|
|
2018-04-14 12:33:36 +00:00
|
|
|
/* makes a pseudo-random int of a given size */
|
2019-05-12 22:22:18 +00:00
|
|
|
mp_err mp_rand_digit(mp_digit *r)
|
2018-04-14 12:33:36 +00:00
|
|
|
{
|
2019-05-12 22:22:18 +00:00
|
|
|
mp_err ret = s_mp_rand_source(r, sizeof(mp_digit));
|
2018-04-14 12:33:36 +00:00
|
|
|
*r &= MP_MASK;
|
|
|
|
return ret;
|
2016-04-09 23:01:29 +00:00
|
|
|
}
|
|
|
|
|
2019-05-12 22:22:18 +00:00
|
|
|
mp_err mp_rand(mp_int *a, int digits)
|
2003-02-28 16:08:34 +00:00
|
|
|
{
|
2019-05-12 22:22:18 +00:00
|
|
|
int i;
|
|
|
|
mp_err ret;
|
2003-02-28 16:08:34 +00:00
|
|
|
|
2017-08-30 18:23:46 +00:00
|
|
|
mp_zero(a);
|
2019-05-07 10:26:46 +00:00
|
|
|
|
2017-08-30 18:23:46 +00:00
|
|
|
if (digits <= 0) {
|
|
|
|
return MP_OKAY;
|
|
|
|
}
|
2003-02-28 16:08:34 +00:00
|
|
|
|
2019-05-07 10:26:46 +00:00
|
|
|
if ((ret = mp_grow(a, digits)) != MP_OKAY) {
|
|
|
|
return ret;
|
|
|
|
}
|
2003-02-28 16:08:34 +00:00
|
|
|
|
2019-05-11 07:09:12 +00:00
|
|
|
if ((ret = s_mp_rand_source(a->dp, (size_t)digits * sizeof(mp_digit))) != MP_OKAY) {
|
2019-05-07 10:26:46 +00:00
|
|
|
return ret;
|
2017-08-30 18:23:46 +00:00
|
|
|
}
|
2003-02-28 16:09:08 +00:00
|
|
|
|
2019-05-07 10:26:46 +00:00
|
|
|
/* TODO: We ensure that the highest digit is nonzero. Should this be removed? */
|
|
|
|
while ((a->dp[digits - 1] & MP_MASK) == 0) {
|
2019-05-11 07:09:12 +00:00
|
|
|
if ((ret = s_mp_rand_source(a->dp + digits - 1, sizeof(mp_digit))) != MP_OKAY) {
|
2019-05-07 10:26:46 +00:00
|
|
|
return ret;
|
2017-08-30 18:23:46 +00:00
|
|
|
}
|
2019-05-07 10:26:46 +00:00
|
|
|
}
|
2017-08-30 18:23:46 +00:00
|
|
|
|
2019-05-07 10:26:46 +00:00
|
|
|
a->used = digits;
|
|
|
|
for (i = 0; i < digits; ++i) {
|
|
|
|
a->dp[i] &= MP_MASK;
|
2017-08-30 18:23:46 +00:00
|
|
|
}
|
2003-02-28 16:08:34 +00:00
|
|
|
|
2017-08-30 18:23:46 +00:00
|
|
|
return MP_OKAY;
|
2003-02-28 16:08:34 +00:00
|
|
|
}
|
2004-10-29 22:07:18 +00:00
|
|
|
#endif
|