Merge pull request #3853 from SparkiDev/sp_add_d

SP int neg add_d/sub_d: handle small values properly
This commit is contained in:
toddouska
2021-03-16 14:16:01 -07:00
committed by GitHub

View File

@ -77,6 +77,7 @@ This library provides single precision (SP) integer math functions.
* called again until complete.
* WOLFSSL_SP_FAST_NCT_EXPTMOD Enables the faster non-constant time modular
* exponentation implementation.
* WOLFSSL_SP_INT_NEGATIVE Enables negative values to be used.
* WOLFSSL_SP_INT_DIGIT_ALIGN Enable when unaligned access of sp_int_digit
* pointer is not allowed.
*/
@ -3107,25 +3108,33 @@ int sp_add_d(sp_int* a, sp_int_digit d, sp_int* r)
{
int err = MP_OKAY;
/* Check validity of parameters. */
if ((a == NULL) || (r == NULL)) {
err = MP_VAL;
}
else
{
#ifndef WOLFSSL_SP_INT_NEGATIVE
/* Positive only so just use internal function. */
err = _sp_add_d(a, d, r);
#else
if (a->sign == MP_ZPOS) {
/* Positive so use interal function. */
r->sign = MP_ZPOS;
err = _sp_add_d(a, d, r);
}
else if ((a->used > 1) || (a->dp[0] > d)) {
/* Negative value bigger than digit so subtract digit. */
r->sign = MP_NEG;
_sp_sub_d(a, d, r);
}
else {
/* Negative value smaller or equal to digit. */
r->sign = MP_ZPOS;
/* Subtract negative value from digit. */
r->dp[0] = d - a->dp[0];
/* Result is a digit equal to or greater than zero. */
r->used = ((r->dp[0] == 0) ? 0 : 1);
}
#endif
}
@ -3149,25 +3158,32 @@ int sp_sub_d(sp_int* a, sp_int_digit d, sp_int* r)
{
int err = MP_OKAY;
/* Check validity of parameters. */
if ((a == NULL) || (r == NULL)) {
err = MP_VAL;
}
else {
#ifndef WOLFSSL_SP_INT_NEGATIVE
/* Positive only so just use internal function. */
_sp_sub_d(a, d, r);
#else
if (a->sign == MP_NEG) {
/* Subtracting from negative use interal add. */
r->sign = MP_NEG;
err = _sp_add_d(a, d, r);
}
else if ((a->used > 1) || (a->dp[0] >= d)) {
/* Positive number greater than digit so add digit. */
r->sign = MP_ZPOS;
_sp_sub_d(a, d, r);
}
else {
/* Negative value smaller than digit. */
r->sign = MP_NEG;
/* Subtract positive value from digit. */
r->dp[0] = d - a->dp[0];
r->used = r->dp[0] > 0;
/* Result is a digit equal to or greater than zero. */
r->used = 1;
}
#endif
}