Commit 64e39ef6 authored by Davide Galassi's avatar Davide Galassi

MPI modular exponentiation is now performed from exponent MSB

Previous implementation was starting from LSB.
The new implementation is a bit more efficient and saves a
temporary mpi variable.
parent cb70da90
......@@ -7,44 +7,35 @@ int cry_mpi_mod_exp(cry_mpi *r, const cry_mpi *b, const cry_mpi *e,
const cry_mpi *m)
{
int res = 0;
size_t bits, i, w;
size_t bits, w;
cry_mpi_digit d;
cry_mpi exp, tmp;
cry_mpi exp;
if (cry_mpi_is_neg(e) || (m != NULL && cry_mpi_is_neg(m)))
return -1;
if ((res = cry_mpi_init_list(&tmp, &exp, NULL)) != 0)
return res;
if (cry_mpi_is_odd(e))
res = cry_mpi_copy(&exp, b);
else
res = cry_mpi_set_int(&exp, 1);
if (res != 0 || (res = cry_mpi_copy(&tmp, b)) != 0)
goto e;
res = cry_mpi_init_int(&exp, 1);
bits = cry_mpi_count_bits(e);
d = 1;
w = 0;
for (i = 1; i < bits; i++) {
if ((res = cry_mpi_sqr(&tmp, &tmp)) != 0 ||
(m != NULL && (res = cry_mpi_mod(&tmp, &tmp, m)) != 0))
d = (cry_mpi_digit)1 << (bits % CRY_MPI_DIGIT_BITS);
w = e->used - 1;
while (bits-- > 0) {
if ((res = cry_mpi_sqr(&exp, &exp)) != 0 ||
(m != NULL && (res = cry_mpi_mod(&exp, &exp, m)) != 0))
goto e;
if (d != ((cry_mpi_digit)1 << (CRY_MPI_DIGIT_BITS-1))) {
d <<= 1;
} else {
d = 1;
w++;
d >>= 1;
if (d == 0) {
d = (cry_mpi_digit)1 << (CRY_MPI_DIGIT_BITS - 1);
w--;
}
if ((e->data[w] & d) != 0) {
if ((res = cry_mpi_mul(&exp, &exp, &tmp)) != 0 ||
if ((res = cry_mpi_mul(&exp, &exp, b)) != 0 ||
(m != NULL && (res = cry_mpi_mod(&exp, &exp, m)) != 0))
goto e;
}
}
cry_mpi_swap(r, &exp);
e: cry_mpi_clear_list(&tmp, &exp, (cry_mpi *) NULL);
e: cry_mpi_clear(&exp);
return res;
}
......@@ -169,7 +169,6 @@ static void mpi_binary_mod_op(int argc, char *argv[], binary_mod_op_f op)
res = op(g_mpi3, g_mpi0, g_mpi1, g_mpi2);
if (*argv[3] != ERROR_FLAG) {
cry_mpi_print(g_mpi3, 16);
ASSERT(res == 0);
ASSERT(cry_mpi_store_str(g_mpi3, 16, (char *)g_buf) == 0);
ASSERT(strcmp((char *)g_buf, argv[3]) == 0);
......
......@@ -461,12 +461,6 @@ mpi_exp
0
1
Exp 1^0
mpi_exp
1
0
1
Exp negative exponent
mpi_exp
aa
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment