diff --git a/wolfcrypt/src/sp_int.c b/wolfcrypt/src/sp_int.c index 422614e3d..d384375b2 100644 --- a/wolfcrypt/src/sp_int.c +++ b/wolfcrypt/src/sp_int.c @@ -402,13 +402,13 @@ int sp_copy(sp_int* a, sp_int* r) /* creates "a" then copies b into it */ int sp_init_copy (sp_int * a, sp_int * b) { - int res; - if ((res = sp_init(a)) == MP_OKAY) { - if((res = sp_copy (b, a)) != MP_OKAY) { + int err; + if ((err = sp_init(a)) == MP_OKAY) { + if((err = sp_copy (b, a)) != MP_OKAY) { sp_clear(a); } } - return res; + return err; } #endif @@ -635,6 +635,8 @@ static void _sp_mul_d(sp_int* a, sp_int_digit n, sp_int* r, int o) static int sp_div(sp_int* a, sp_int* d, sp_int* r, sp_int* rem) { int err = MP_OKAY; + int ret; + int done = 0; int i; int s; sp_int_word w = 0; @@ -655,8 +657,24 @@ static int sp_div(sp_int* a, sp_int* d, sp_int* r, sp_int* rem) if (sp_iszero(d)) err = MP_VAL; + ret = sp_cmp(a, d); + if (ret == MP_LT) { + sp_copy(a, rem); + if (r != NULL) { + sp_set(r, 0); + } + done = 1; + } + else if (ret == MP_EQ) { + sp_set(rem, 0); + if (r != NULL) { + sp_set(r, 1); + } + done = 1; + } + #ifdef WOLFSSL_SMALL_STACK - if (err == MP_OKAY) { + if (!done && err == MP_OKAY) { sa = (sp_int*)XMALLOC(sizeof(sp_int) * 4, NULL, DYNAMIC_TYPE_BIGINT); if (sa == NULL) err = MP_MEM; @@ -668,7 +686,7 @@ static int sp_div(sp_int* a, sp_int* d, sp_int* r, sp_int* rem) } #endif - if (err == MP_OKAY) { + if (!done && err == MP_OKAY) { sp_init(sa); sp_init(sd); sp_init(tr); @@ -685,26 +703,29 @@ static int sp_div(sp_int* a, sp_int* d, sp_int* r, sp_int* rem) } tr->used = sa->used - d->used; - if ((sa->dp[sa->used-1] >> (SP_WORD_SIZE - 1)) == 1) { - _sp_mul_d(d, 1, trial, sa->used - d->used); - if (sp_cmp(sa, trial) != MP_LT) { - tr->used++; - sp_sub(sa, trial, sa); - tr->dp[sa->used - d->used] = 1; - } - } - + sp_clear(tr); dt = d->dp[d->used-1]; for (i = sa->used - 1; i >= d->used; i--) { w = ((sp_int_word)sa->dp[i] << SP_WORD_SIZE) | sa->dp[i-1]; - t = (sp_int_digit)(w / dt); - _sp_mul_d(d, t, trial, i - d->used); - while (sp_cmp(trial, sa) == MP_GT) { - t--; - _sp_mul_d(d, t, trial, i - d->used); + w /= dt; + if (w > (sp_int_digit)-1) { + t = (sp_int_digit)-1; + } + else { + t = (sp_int_digit)w; + } + if (t > 0) { + _sp_mul_d(d, t, trial, i - d->used); + while (sp_cmp(trial, sa) == MP_GT) { + t--; + _sp_mul_d(d, t, trial, i - d->used); + } + sp_sub(sa, trial, sa); + tr->dp[i - d->used] += t; + if (w > (sp_int_digit)-1) { + i++; + } } - sp_sub(sa, trial, sa); - tr->dp[i - d->used] = t; } sp_clamp(tr); @@ -1882,7 +1903,7 @@ int sp_prime_is_prime_ex(sp_int* a, int t, int* result, WC_RNG* rng) } #ifndef NO_DH -int sp_exch (sp_int* a, sp_int* b) +int sp_exch(sp_int* a, sp_int* b) { int err = MP_OKAY; #ifndef WOLFSSL_SMALL_STACK