diff --git a/wolfcrypt/src/tfm.c b/wolfcrypt/src/tfm.c index fe8f5bffe9..65dc7a0f3b 100644 --- a/wolfcrypt/src/tfm.c +++ b/wolfcrypt/src/tfm.c @@ -138,9 +138,31 @@ int s_fp_add(fp_int *a, fp_int *b, fp_int *c) oldused = MIN(c->used, FP_SIZE); /* help static analysis w/ largest size */ c->used = y; - t = 0; + t = 0; /* Our running total starts at zero. */ for (x = 0; x < y; x++) { - t += ((fp_word)a->dp[x]) + ((fp_word)b->dp[x]); + if ( (x < a->used) && (x < b->used) ) { + /* x is less than both [a].used and [b].used, so we add both */ + t += ((fp_word)a->dp[x]) + ((fp_word)b->dp[x]); + } + else { + /* Here we honor the actual [a].used and [b].used values + * and NOT assume that values beyond [used] are zero. */ + if ((x >= a->used) && (x < b->used)) { + /* x more than [a].used, [b] ok, so just add [b] */ + t += /* ((fp_word)(0)) + */ ((fp_word)b->dp[x]); + } + else { + if ((x < a->used) && (x >= b->used)) { + /* x more than [b].used, [a] ok, so just add [a] */ + t += ((fp_word)a->dp[x]) /* + (fp_word)(0) */; + } + else { + /* we should never get here, as a.used cannot be greater + * than b.used, while b.used is greater than a.used! */ + /* t += 0 + 0 */ + } /* nothing added */ + } /* else only a added */ + } /* else only a or only b added */ c->dp[x] = (fp_digit)t; t >>= DIGIT_BIT; }