Skip to content

s_mp_invmod_odd returns wrong result for negative numbers #534

@friedrichsenm

Description

@friedrichsenm

Using mp_invod can return incorrect results for negative numbers. Using it to find the inverse of -1 mod 7 yields -6 instead of 6. The problem looks like it could be because of a couple of places:

/* we need y = |a| */
if ((err = mp_mod(a, b, &y)) != MP_OKAY) goto LBL_ERR;

The comment is assuming that mp_mod gives the absolute value, but it doesn't. It will make the value positive though.

Then, in

sign = a->sign;
while (mp_isneg(&D)) {
if ((err = mp_add(&D, b, &D)) != MP_OKAY) goto LBL_ERR;
}
/* too big */
while (mp_cmp_mag(&D, b) != MP_LT) {
if ((err = mp_sub(&D, b, &D)) != MP_OKAY) goto LBL_ERR;
}
mp_exch(&D, c);
c->sign = sign;

the sign of a is used to flip the sign of the inverse, but the sign should already be correct since mp_mod is using a positive member of the equivalence class for a. Removing this sign change should fix it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions