Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bignum: Extract secp384r1 fast reduction from the prototype #7222

33 changes: 33 additions & 0 deletions library/ecp_curves.c
Original file line number Diff line number Diff line change
Expand Up @@ -5299,6 +5299,39 @@ int mbedtls_ecp_mod_p384_raw(mbedtls_mpi_uint *X, size_t X_limbs)
MBEDTLS_ECP_DP_SECP256R1_ENABLED ||
MBEDTLS_ECP_DP_SECP384R1_ENABLED */

#if defined(MBEDTLS_TEST_HOOKS) && defined(MBEDTLS_ECP_C)
MBEDTLS_STATIC_TESTABLE
void mbedtls_ecp_fix_negative(mbedtls_mpi *N, signed char c, size_t bits)
{
size_t i;

/* Set N := 2^bits - 1 - N. We know that 0 <= N < 2^bits, so
* set the absolute value to 0xfff...fff - N. There is no carry
* since we're subtracting from all-bits-one. */
for (i = 0; i <= bits / 8 / sizeof(mbedtls_mpi_uint); i++) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Repeating bits / 8 / sizeof(mbedtls_mpi_uint) - can we have a variable for this please?

Copy link
Contributor Author

@minosgalanakis minosgalanakis Mar 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function is not new, it was just moved further down the code. I would rather not modify it since it falls out of the scope of this PR

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay

N->p[i] = ~(mbedtls_mpi_uint) 0 - N->p[i];
}
/* Add 1, taking care of the carry. */
i = 0;
do {
++N->p[i];
} while (N->p[i++] == 0 && i <= bits / 8 / sizeof(mbedtls_mpi_uint));
/* Invert the sign.
* Now N = N0 - 2^bits where N0 is the initial value of N. */
N->s = -1;

/* Add |c| * 2^bits to the absolute value. Since c and N are
* negative, this adds c * 2^bits. */
mbedtls_mpi_uint msw = (mbedtls_mpi_uint) -c;
#if defined(MBEDTLS_HAVE_INT64)
if (bits == 224) {
msw <<= 32;
}
#endif
N->p[bits / 8 / sizeof(mbedtls_mpi_uint)] += msw;
}
#endif /* MBEDTLS_TEST_HOOKS & MBEDTLS_ECP_C */

#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
/* Size of p521 in terms of mbedtls_mpi_uint */
#define P521_WIDTH (521 / 8 / sizeof(mbedtls_mpi_uint) + 1)
Expand Down