From b0ec2bf05843edf27a19da29c8817cd92ef307cf Mon Sep 17 00:00:00 2001 From: Daniel Pouzzner Date: Fri, 18 Dec 2020 02:05:18 -0600 Subject: [PATCH] wolfcrypt/src/integer.c: fix mp_read_unsigned_bin() accounting on mp_int.used_bits to avoid spurious .used > .alloc condition at loop exit. --- wolfcrypt/src/integer.c | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/wolfcrypt/src/integer.c b/wolfcrypt/src/integer.c index badf70994..7bfba65b4 100644 --- a/wolfcrypt/src/integer.c +++ b/wolfcrypt/src/integer.c @@ -697,10 +697,18 @@ int mp_mod_2d (mp_int * a, int b, mp_int * c) int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c) { int res; + int digits_needed; - /* make sure there are at least two digits */ - if (a->alloc < 2) { - if ((res = mp_grow(a, 2)) != MP_OKAY) { + while (c > 0 && b[0] == 0) { + c--; + b++; + } + + digits_needed = ((c * CHAR_BIT) + DIGIT_BIT - 1) / DIGIT_BIT; + + /* make sure there are enough digits available */ + if (a->alloc < digits_needed) { + if ((res = mp_grow(a, digits_needed)) != MP_OKAY) { return res; } } @@ -716,11 +724,13 @@ int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c) #ifndef MP_8BIT a->dp[0] |= *b++; - a->used += 1; + if (a->used == 0) + a->used = 1; #else a->dp[0] = (*b & MP_MASK); a->dp[1] |= ((*b++ >> 7U) & 1); - a->used += 2; + if (a->used == 0) + a->used = 2; #endif } mp_clamp (a);