Skip to content

Commit 243bb78

Browse files
committed
Clear the mp_int in mp_rand so a wider prior value cannot survive
1 parent 85964c6 commit 243bb78

2 files changed

Lines changed: 11 additions & 2 deletions

File tree

‎tests/api/test_wolfmath.c‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,7 @@ int test_mp_rand(void)
352352
mp_int a;
353353
WC_RNG rng;
354354
int digits = 1;
355+
byte wide[5 * sizeof(mp_digit)];
355356

356357
XMEMSET(&a, 0, sizeof(mp_int));
357358
XMEMSET(&rng, 0, sizeof(WC_RNG));
@@ -366,12 +367,19 @@ int test_mp_rand(void)
366367
* rejected: drives the "digits > size" operand of that guard true (the
367368
* valid call below drives it false). This rejection only exists on the
368369
* fixed-size backends; USE_INTEGER_HEAP_MATH grows the mp_int instead
369-
* (mp_set_bit) and would legally succeed (and force a large allocation),
370+
* (mp_2expt) and would legally succeed (and force a large allocation),
370371
* so the vector is limited to the fixed-size backends. */
371372
#ifndef USE_INTEGER_HEAP_MATH
372373
ExpectIntNE(mp_rand(&a, 100000, &rng), 0);
373374
#endif
374375
ExpectIntEQ(mp_rand(&a, digits, &rng), 0);
376+
/* A wider value already in a must not survive into the result. */
377+
XMEMSET(wide, 0xff, sizeof(wide));
378+
ExpectIntEQ(mp_read_unsigned_bin(&a, wide, (word32)sizeof(wide)),
379+
MP_OKAY);
380+
ExpectIntEQ(mp_rand(&a, 2, &rng), 0);
381+
ExpectIntLE(mp_count_bits(&a), 2 * DIGIT_BIT);
382+
ExpectIntGT(mp_count_bits(&a), DIGIT_BIT);
375383

376384
mp_clear(&a);
377385
DoExpectIntEQ(wc_FreeRng(&rng), 0);

‎wolfcrypt/src/wolfmath.c‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,8 @@ int mp_rand(mp_int* a, int digits, WC_RNG* rng)
180180
#ifdef USE_INTEGER_HEAP_MATH
181181
/* allocate space for digits */
182182
if (ret == MP_OKAY) {
183-
ret = mp_set_bit(a, digits * DIGIT_BIT - 1);
183+
/* Zeroed first, so no wider value already in a survives. */
184+
ret = mp_2expt(a, digits * DIGIT_BIT - 1);
184185
}
185186
#else
186187
#if defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_SP_MATH_ALL)

0 commit comments

Comments
 (0)