3 * Modular exponentiation with Montgomery reduction
5 * (c) 2004 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Catacomb.
12 * Catacomb is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
17 * Catacomb is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public
23 * License along with Catacomb; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28 /*----- Header files ------------------------------------------------------*/
32 #include "mpmont-exp.h"
34 /*----- Exponentiation ----------------------------------------------------*/
36 /* --- @mpmont_expr@ --- *
38 * Arguments: @const mpmont *mm@ = pointer to Montgomery reduction context
39 * @mp *d@ = fake destination
43 * Returns: Result, %$(a R^{-1})^e R \bmod m$%.
46 mp
*mpmont_expr(const mpmont
*mm
, mp
*d
, mp
*a
, mp
*e
)
48 mp
*x
= MP_COPY(mm
->r
);
49 mp
*spare
= (e
->f
& MP_BURN
) ? MP_NEWSEC
: MP_NEW
;
57 a
= mpmont_reduce(mm
, a
, a
);
58 a
= mp_modinv(a
, a
, mm
->m
);
59 a
= mpmont_mul(mm
, a
, a
, mm
->r2
);
61 if (MP_LEN(e
) < EXP_THRESH
)
72 /* --- @mpmont_exp@ --- *
74 * Arguments: @const mpmont *mm@ = pointer to Montgomery reduction context
75 * @mp *d@ = fake destination
79 * Returns: Result, %$a^e \bmod m$%.
82 mp
*mpmont_exp(const mpmont
*mm
, mp
*d
, mp
*a
, mp
*e
)
85 d
= mpmont_mul(mm
, d
, a
, mm
->r2
);
86 d
= mpmont_expr(mm
, d
, d
, e
);
87 d
= mpmont_reduce(mm
, d
, d
);
92 /*----- Test rig ----------------------------------------------------------*/
96 static int texp(dstr
*v
)
98 mp
*m
= *(mp
**)v
[0].buf
;
99 mp
*a
= *(mp
**)v
[1].buf
;
100 mp
*b
= *(mp
**)v
[2].buf
;
101 mp
*r
= *(mp
**)v
[3].buf
;
106 mpmont_create(&mm
, m
);
108 mr
= mpmont_exp(&mm
, MP_NEW
, a
, b
);
111 fputs("\n*** montgomery modexp failed", stderr
);
112 fputs("\n m = ", stderr
); mp_writefile(m
, stderr
, 10);
113 fputs("\n a = ", stderr
); mp_writefile(a
, stderr
, 10);
114 fputs("\n e = ", stderr
); mp_writefile(b
, stderr
, 10);
115 fputs("\n r = ", stderr
); mp_writefile(r
, stderr
, 10);
116 fputs("\nmr = ", stderr
); mp_writefile(mr
, stderr
, 10);
127 assert(mparena_count(MPARENA_GLOBAL
) == 0);
131 static test_chunk tests
[] = {
132 { "exp", texp
, { &type_mp
, &type_mp
, &type_mp
, &type_mp
, 0 } },
136 int main(int argc
, char *argv
[])
139 test_run(argc
, argv
, tests
, SRCDIR
"/t/mpmont");
145 /*----- That's all, folks -------------------------------------------------*/