3 * General-purpose modular exponentiation
5 * (c) 2006 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 ------------------------------------------------------*/
31 #include "mpbarrett.h"
34 /*----- Main code ---------------------------------------------------------*/
36 /* --- @mp_modexp@ --- *
38 * Arguments: @mp *d@ = fake destination
39 * @mp *x@ = base of exponentiation
41 * @mp *n@ = modulus (must be positive)
43 * Returns: The value %$x^e \bmod n$%.
46 mp *mp_modexp(mp *d, mp *x, mp *e, mp *n)
50 mpmont_create(&mm, n);
51 d = mpmont_exp(&mm, d, x, e);
55 mpbarrett_create(&mb, n);
56 d = mpbarrett_exp(&mb, d, x, e);
57 mpbarrett_destroy(&mb);
62 /*----- Test rig ----------------------------------------------------------*/
66 static int tmodexp(dstr *v)
68 mp *a = *(mp **)v[0].buf;
69 mp *b = *(mp **)v[1].buf;
70 mp *m = *(mp **)v[2].buf;
71 mp *r = *(mp **)v[3].buf;
75 mr = mp_modexp(MP_NEW, a, b, m);
78 fputs("\n*** modexp failed", stderr);
79 fputs("\n a = ", stderr); mp_writefile(a, stderr, 10);
80 fputs("\n e = ", stderr); mp_writefile(b, stderr, 10);
81 fputs("\n m = ", stderr); mp_writefile(m, stderr, 10);
82 fputs("\n r = ", stderr); mp_writefile(r, stderr, 10);
83 fputs("\nmr = ", stderr); mp_writefile(mr, stderr, 10);
93 assert(mparena_count(MPARENA_GLOBAL) == 0);
97 static test_chunk tests[] = {
98 { "modexp", tmodexp, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
102 int main(int argc, char *argv[])
105 test_run(argc, argv, tests, SRCDIR "/t/mp");
111 /*----- That's all, folks -------------------------------------------------*/