2020-12-28 21:40:37 +00:00
|
|
|
#include "tommath_private.h"
|
2014-12-10 21:56:49 +00:00
|
|
|
#ifdef BN_MP_RAND_C
|
2020-12-28 21:40:37 +00:00
|
|
|
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
|
|
|
|
/* SPDX-License-Identifier: Unlicense */
|
2014-12-10 21:56:49 +00:00
|
|
|
|
2020-12-28 21:40:37 +00:00
|
|
|
/* Dropbear sets this separately, avoid platform code */
|
|
|
|
mp_err(*s_mp_rand_source)(void *out, size_t size) = NULL;
|
2019-06-09 20:44:26 +00:00
|
|
|
|
2020-12-28 21:40:37 +00:00
|
|
|
void mp_rand_source(mp_err(*source)(void *out, size_t size))
|
2019-06-09 20:44:26 +00:00
|
|
|
{
|
2020-12-28 21:40:37 +00:00
|
|
|
/* Dropbear, don't reset to platform if source==NULL */
|
|
|
|
s_mp_rand_source = source;
|
2019-06-09 20:44:26 +00:00
|
|
|
}
|
|
|
|
|
2020-12-28 21:40:37 +00:00
|
|
|
mp_err mp_rand(mp_int *a, int digits)
|
2014-12-10 21:56:49 +00:00
|
|
|
{
|
2020-12-28 21:40:37 +00:00
|
|
|
int i;
|
|
|
|
mp_err err;
|
|
|
|
|
|
|
|
mp_zero(a);
|
2014-12-10 21:56:49 +00:00
|
|
|
|
2020-12-28 21:40:37 +00:00
|
|
|
if (digits <= 0) {
|
|
|
|
return MP_OKAY;
|
|
|
|
}
|
2014-12-10 21:56:49 +00:00
|
|
|
|
2020-12-28 21:40:37 +00:00
|
|
|
if ((err = mp_grow(a, digits)) != MP_OKAY) {
|
|
|
|
return err;
|
|
|
|
}
|
2014-12-10 21:56:49 +00:00
|
|
|
|
2020-12-28 21:40:37 +00:00
|
|
|
if ((err = s_mp_rand_source(a->dp, (size_t)digits * sizeof(mp_digit))) != MP_OKAY) {
|
|
|
|
return err;
|
|
|
|
}
|
2014-12-10 21:56:49 +00:00
|
|
|
|
2020-12-28 21:40:37 +00:00
|
|
|
/* TODO: We ensure that the highest digit is nonzero. Should this be removed? */
|
|
|
|
while ((a->dp[digits - 1] & MP_MASK) == 0u) {
|
|
|
|
if ((err = s_mp_rand_source(a->dp + digits - 1, sizeof(mp_digit))) != MP_OKAY) {
|
|
|
|
return err;
|
|
|
|
}
|
|
|
|
}
|
2014-12-10 21:56:49 +00:00
|
|
|
|
2020-12-28 21:40:37 +00:00
|
|
|
a->used = digits;
|
|
|
|
for (i = 0; i < digits; ++i) {
|
|
|
|
a->dp[i] &= MP_MASK;
|
|
|
|
}
|
2014-12-10 21:56:49 +00:00
|
|
|
|
2020-12-28 21:40:37 +00:00
|
|
|
return MP_OKAY;
|
2014-12-10 21:56:49 +00:00
|
|
|
}
|
|
|
|
#endif
|