2023-12-06 17:43:39 -05:00
|
|
|
/* tests the montgomery routines */
|
|
|
|
#include <tommath.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <time.h>
|
|
|
|
|
|
|
|
int main(void)
|
|
|
|
{
|
|
|
|
mp_int modulus, R, p, pp;
|
|
|
|
mp_digit mp;
|
2024-06-17 19:04:36 -04:00
|
|
|
mp_err err;
|
2023-12-06 17:43:39 -05:00
|
|
|
int x, y;
|
|
|
|
|
|
|
|
srand(time(NULL));
|
2024-06-17 19:04:36 -04:00
|
|
|
if ((err = mp_init_multi(&modulus, &R, &p, &pp, NULL)) != MP_OKAY) goto LTM_ERR;
|
2023-12-06 17:43:39 -05:00
|
|
|
|
|
|
|
/* loop through various sizes */
|
|
|
|
for (x = 4; x < 256; x++) {
|
|
|
|
printf("DIGITS == %3d...", x);
|
|
|
|
fflush(stdout);
|
|
|
|
|
|
|
|
/* make up the odd modulus */
|
2024-06-17 19:04:36 -04:00
|
|
|
if ((err = mp_rand(&modulus, x)) != MP_OKAY) goto LTM_ERR;
|
2023-12-06 17:43:39 -05:00
|
|
|
modulus.dp[0] |= 1uL;
|
|
|
|
|
|
|
|
/* now find the R value */
|
2024-06-17 19:04:36 -04:00
|
|
|
if ((err = mp_montgomery_calc_normalization(&R, &modulus)) != MP_OKAY) goto LTM_ERR;
|
|
|
|
if ((err = mp_montgomery_setup(&modulus, &mp)) != MP_OKAY) goto LTM_ERR;
|
2023-12-06 17:43:39 -05:00
|
|
|
|
|
|
|
/* now run through a bunch tests */
|
|
|
|
for (y = 0; y < 1000; y++) {
|
2024-06-17 19:04:36 -04:00
|
|
|
/* p = random */
|
|
|
|
if ((err = mp_rand(&p, x/2)) != MP_OKAY) goto LTM_ERR;
|
|
|
|
/* pp = R * p */
|
|
|
|
if ((err = mp_mul(&p, &R, &pp)) != MP_OKAY) goto LTM_ERR;
|
|
|
|
if ((err = mp_montgomery_reduce(&pp, &modulus, mp)) != MP_OKAY) goto LTM_ERR;
|
2023-12-06 17:43:39 -05:00
|
|
|
|
|
|
|
/* should be equal to p */
|
|
|
|
if (mp_cmp(&pp, &p) != MP_EQ) {
|
|
|
|
printf("FAILURE!\n");
|
|
|
|
exit(-1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
printf("PASSED\n");
|
|
|
|
}
|
|
|
|
|
2024-06-17 19:04:36 -04:00
|
|
|
LTM_ERR:
|
2023-12-06 17:43:39 -05:00
|
|
|
return 0;
|
|
|
|
}
|