* gpgkeys_hkp.c (send_key), gpgkeys_ldap.c (send_key, send_key_keyserver):
[gnupg.git] / mpi / mpi-mpow.c
blob9a186103a759d7182e46b0433681fe999d948a74
1 /* mpi-mpow.c - MPI functions
2 * Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19 * USA.
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include "mpi-internal.h"
26 #include "longlong.h"
27 #include <assert.h>
29 static int
30 build_index( MPI *exparray, int k, int i, int t )
32 int j, bitno;
33 int idx = 0;
35 bitno = t-i;
36 for(j=k-1; j >= 0; j-- ) {
37 idx <<= 1;
38 if( mpi_test_bit( exparray[j], bitno ) )
39 idx |= 1;
41 return idx;
44 /****************
45 * RES = (BASE[0] ^ EXP[0]) * (BASE[1] ^ EXP[1]) * ... * mod M
47 void
48 mpi_mulpowm( MPI res, MPI *basearray, MPI *exparray, MPI m)
50 int k; /* number of elements */
51 int t; /* bit size of largest exponent */
52 int i, j, idx;
53 MPI *G; /* table with precomputed values of size 2^k */
54 MPI tmp;
56 for(k=0; basearray[k]; k++ )
58 assert(k);
59 for(t=0, i=0; (tmp=exparray[i]); i++ ) {
60 j = mpi_get_nbits(tmp);
61 if( j > t )
62 t = j;
64 assert(i==k);
65 assert(t);
66 assert( k < 10 );
68 G = xmalloc_clear( (1<<k) * sizeof *G );
69 /* and calculate */
70 tmp = mpi_alloc( mpi_get_nlimbs(m)+1 );
71 mpi_set_ui( res, 1 );
72 for(i = 1; i <= t; i++ ) {
73 mpi_mulm(tmp, res, res, m );
74 idx = build_index( exparray, k, i, t );
75 assert( idx >= 0 && idx < (1<<k) );
76 if( !G[idx] ) {
77 if( !idx )
78 G[0] = mpi_alloc_set_ui( 1 );
79 else {
80 for(j=0; j < k; j++ ) {
81 if( (idx & (1<<j) ) ) {
82 if( !G[idx] )
83 G[idx] = mpi_copy( basearray[j] );
84 else
85 mpi_mulm( G[idx], G[idx], basearray[j], m );
88 if( !G[idx] )
89 G[idx] = mpi_alloc(0);
92 mpi_mulm(res, tmp, G[idx], m );
95 /* cleanup */
96 mpi_free(tmp);
97 for(i=0; i < (1<<k); i++ )
98 mpi_free(G[i]);
99 xfree(G);