OSDN Git Service

2013.10.24
[uclinux-h8/uClinux-dist.git] / freeswan / pluto / elgamal.c
1 /* elgamal.c  -  ElGamal Public Key encryption
2  *      Copyright (C) 1998 Free Software Foundation, Inc.
3  *
4  * For a description of the algorithm, see:
5  *   Bruce Schneier: Applied Cryptography. John Wiley & Sons, 1996.
6  *   ISBN 0-471-11709-9. Pages 476 ff.
7  *
8  * This file is part of GnuPG.
9  *
10  * GnuPG is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * GnuPG is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
23  */
24
25 #ifdef PLUTO
26 #include <gmp.h>
27 #include <freeswan.h>
28 #include "constants.h"
29 #include "defs.h"
30 #include "log.h"
31 #include "rnd.h"
32 #include "gcryptfix.h"
33 #else /*! PLUTO */
34 /* #include <config.h> */
35 #endif /* !PLUTO */
36
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40
41 #ifndef PLUTO
42 /* #include "util.h" */
43 /* #include "mpi.h" */
44 /* #include "cipher.h" */
45 #endif
46
47 #include "elgamal.h"
48
49 typedef struct {
50     MPI p;          /* prime */
51     MPI g;          /* group generator */
52     MPI y;          /* g^x mod p */
53 } ELG_public_key;
54
55
56 typedef struct {
57     MPI p;          /* prime */
58     MPI g;          /* group generator */
59     MPI y;          /* g^x mod p */
60     MPI x;          /* secret exponent */
61 } ELG_secret_key;
62
63
64 static void test_keys( ELG_secret_key *sk, unsigned nbits );
65 static MPI gen_k( MPI p );
66 static void generate( ELG_secret_key *sk, unsigned nbits, MPI **factors );
67 static int  check_secret_key( ELG_secret_key *sk );
68 static void encrypt(MPI a, MPI b, MPI input, ELG_public_key *pkey );
69 static void decrypt(MPI output, MPI a, MPI b, ELG_secret_key *skey );
70 static void sign(MPI a, MPI b, MPI input, ELG_secret_key *skey);
71 static int  verify(MPI a, MPI b, MPI input, ELG_public_key *pkey);
72
73
74 static void
75 progress( int c )
76 {
77     fputc( c, stderr );
78 }
79
80
81 static void
82 test_keys( ELG_secret_key *sk, unsigned nbits )
83 {
84     ELG_public_key pk;
85     MPI test = mpi_alloc( 0 );
86     MPI out1_a = mpi_alloc( nbits / BITS_PER_MPI_LIMB );
87     MPI out1_b = mpi_alloc( nbits / BITS_PER_MPI_LIMB );
88     MPI out2 = mpi_alloc( nbits / BITS_PER_MPI_LIMB );
89
90     pk.p = sk->p;
91     pk.g = sk->g;
92     pk.y = sk->y;
93
94     /*mpi_set_bytes( test, nbits, get_random_byte, 0 );*/
95     {   char *p = get_random_bits( nbits, 0, 0 );
96         mpi_set_buffer( test, p, (nbits+7)/8, 0 );
97         m_free(p);
98     }
99
100     encrypt( out1_a, out1_b, test, &pk );
101     decrypt( out2, out1_a, out1_b, sk );
102     if( mpi_cmp( test, out2 ) )
103         log_fatal("ElGamal operation: encrypt, decrypt failed\n");
104
105     sign( out1_a, out1_b, test, sk );
106     if( !verify( out1_a, out1_b, test, &pk ) )
107         log_fatal("ElGamal operation: sign, verify failed\n");
108
109     mpi_free( test );
110     mpi_free( out1_a );
111     mpi_free( out1_b );
112     mpi_free( out2 );
113 }
114
115
116 /****************
117  * generate a random secret exponent k from prime p, so
118  * that k is relatively prime to p-1
119  */
120 static MPI
121 gen_k( MPI p )
122 {
123     MPI k = mpi_alloc_secure( 0 );
124     MPI temp = mpi_alloc( mpi_get_nlimbs(p) );
125     MPI p_1 = mpi_copy(p);
126     unsigned int nbits = mpi_get_nbits(p);
127     unsigned int nbytes = (nbits+7)/8;
128     char *rndbuf = NULL;
129
130     if( DBG_CIPHER )
131         log_debug("choosing a random k ");
132     mpi_sub_ui( p_1, p, 1);
133     for(;;) {
134         if( DBG_CIPHER )
135             progress('.');
136         if( !rndbuf || nbits < 32 ) {
137             m_free(rndbuf);
138             rndbuf = get_random_bits( nbits, 1, 1 );
139         }
140         else { /* change only some of the higher bits */
141             /* we could imporove this by directly requesting more memory
142              * at the first call to get_random_bits() and use this the here
143              * maybe it is easier to do this directly in random.c */
144             char *pp = get_random_bits( 32, 1, 1 );
145             memcpy( rndbuf,pp, 4 );
146             m_free(pp);
147         }
148         mpi_set_buffer( k, rndbuf, nbytes, 0 );
149
150         for(;;) {
151             /* make sure that the number is of the exact lenght */
152             if( mpi_test_bit( k, nbits-1 ) )
153                 mpi_set_highbit( k, nbits-1 );
154             else {
155                 mpi_set_highbit( k, nbits-1 );
156                 mpi_clear_bit( k, nbits-1 );
157             }
158             if( !(mpi_cmp( k, p_1 ) < 0) ) {  /* check: k < (p-1) */
159                 if( DBG_CIPHER )
160                     progress('+');
161                 break; /* no  */
162             }
163             if( !(mpi_cmp_ui( k, 0 ) > 0) ) { /* check: k > 0 */
164                 if( DBG_CIPHER )
165                     progress('-');
166                 break; /* no */
167             }
168             if( mpi_gcd( temp, k, p_1 ) )
169                 goto found;  /* okay, k is relatively prime to (p-1) */
170             mpi_add_ui( k, k, 1 );
171         }
172     }
173   found:
174     m_free(rndbuf);
175     if( DBG_CIPHER )
176         progress('\n');
177     mpi_free(p_1);
178     mpi_free(temp);
179
180     return k;
181 }
182
183 /****************
184  * Generate a key pair with a key of size NBITS
185  * Returns: 2 structures filles with all needed values
186  *          and an array with n-1 factors of (p-1)
187  */
188 static void
189 generate(  ELG_secret_key *sk, unsigned nbits, MPI **ret_factors )
190 {
191     MPI p;    /* the prime */
192     MPI p_min1;
193     MPI g;
194     MPI x;    /* the secret exponent */
195     MPI y;
196     MPI temp;
197     unsigned qbits;
198     byte *rndbuf;
199
200     p_min1 = mpi_alloc( (nbits+BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB );
201     temp   = mpi_alloc( (nbits+BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB );
202     if( nbits < 512 )
203         qbits = 120;
204     else if( nbits <= 1024 )
205         qbits = 160;
206     else if( nbits <= 2048 )
207         qbits = 200;
208     else
209         qbits = 240;
210     g = mpi_alloc(1);
211     p = generate_elg_prime( 0, nbits, qbits, g, ret_factors );
212     mpi_sub_ui(p_min1, p, 1);
213
214
215     /* select a random number which has these properties:
216      *   0 < x < p-1
217      * This must be a very good random number because this is the
218      * secret part.  The prime is public and may be shared anyway,
219      * so a random generator level of 1 is used for the prime.
220      */
221     x = mpi_alloc_secure( nbits/BITS_PER_MPI_LIMB );
222     if( DBG_CIPHER )
223         log_debug("choosing a random x ");
224     rndbuf = NULL;
225     do {
226         if( DBG_CIPHER )
227             progress('.');
228         if( rndbuf ) { /* change only some of the higher bits */
229             if( nbits < 16 ) {/* should never happen ... */
230                 m_free(rndbuf);
231                 rndbuf = get_random_bits( nbits, 2, 1 );
232             }
233             else {
234                 char *r = get_random_bits( 16, 2, 1 );
235                 memcpy(rndbuf, r, 16/8 );
236                 m_free(r);
237             }
238         }
239         else
240             rndbuf = get_random_bits( nbits, 2, 1 );
241         mpi_set_buffer( x, rndbuf, (nbits+7)/8, 0 );
242         mpi_clear_highbit( x, nbits+1 );
243     } while( !( mpi_cmp_ui( x, 0 )>0 && mpi_cmp( x, p_min1 )<0 ) );
244     m_free(rndbuf);
245
246     y = mpi_alloc(nbits/BITS_PER_MPI_LIMB);
247     mpi_powm( y, g, x, p );
248
249     if( DBG_CIPHER ) {
250         progress('\n');
251         log_mpidump("elg  p= ", p );
252         log_mpidump("elg  g= ", g );
253         log_mpidump("elg  y= ", y );
254         log_mpidump("elg  x= ", x );
255     }
256
257     /* copy the stuff to the key structures */
258     sk->p = p;
259     sk->g = g;
260     sk->y = y;
261     sk->x = x;
262
263     /* now we can test our keys (this should never fail!) */
264     test_keys( sk, nbits - 64 );
265
266     mpi_free( p_min1 );
267     mpi_free( temp   );
268 }
269
270
271 /****************
272  * Test whether the secret key is valid.
273  * Returns: if this is a valid key.
274  */
275 static int
276 check_secret_key( ELG_secret_key *sk )
277 {
278     int rc;
279     MPI y = mpi_alloc( mpi_get_nlimbs(sk->y) );
280
281     mpi_powm( y, sk->g, sk->x, sk->p );
282     rc = !mpi_cmp( y, sk->y );
283     mpi_free( y );
284     return rc;
285 }
286
287
288 static void
289 encrypt(MPI a, MPI b, MPI input, ELG_public_key *pkey )
290 {
291     MPI k;
292
293     /* Note: maybe we should change the interface, so that it
294      * is possible to check that input is < p and return an
295      * error code.
296      */
297
298     k = gen_k( pkey->p );
299     mpi_powm( a, pkey->g, k, pkey->p );
300     /* b = (y^k * input) mod p
301      *   = ((y^k mod p) * (input mod p)) mod p
302      * and because input is < p
303      *   = ((y^k mod p) * input) mod p
304      */
305     mpi_powm( b, pkey->y, k, pkey->p );
306     mpi_mulm( b, b, input, pkey->p );
307   #if 0
308     if( DBG_CIPHER ) {
309         log_mpidump("elg encrypted y= ", pkey->y);
310         log_mpidump("elg encrypted p= ", pkey->p);
311         log_mpidump("elg encrypted k= ", k);
312         log_mpidump("elg encrypted M= ", input);
313         log_mpidump("elg encrypted a= ", a);
314         log_mpidump("elg encrypted b= ", b);
315     }
316   #endif
317     mpi_free(k);
318 }
319
320
321
322
323 static void
324 decrypt(MPI output, MPI a, MPI b, ELG_secret_key *skey )
325 {
326     MPI t1 = mpi_alloc_secure( mpi_get_nlimbs( skey->p ) );
327
328     /* output = b/(a^x) mod p */
329
330     mpi_powm( t1, a, skey->x, skey->p );
331     mpi_invm( t1, t1, skey->p );
332     mpi_mulm( output, b, t1, skey->p );
333   #if 0
334     if( DBG_CIPHER ) {
335         log_mpidump("elg decrypted x= ", skey->x);
336         log_mpidump("elg decrypted p= ", skey->p);
337         log_mpidump("elg decrypted a= ", a);
338         log_mpidump("elg decrypted b= ", b);
339         log_mpidump("elg decrypted M= ", output);
340     }
341   #endif
342     mpi_free(t1);
343 }
344
345
346 /****************
347  * Make an Elgamal signature out of INPUT
348  */
349
350 static void
351 sign(MPI a, MPI b, MPI input, ELG_secret_key *skey )
352 {
353     MPI k;
354     MPI t   = mpi_alloc( mpi_get_nlimbs(a) );
355     MPI inv = mpi_alloc( mpi_get_nlimbs(a) );
356     MPI p_1 = mpi_copy(skey->p);
357
358    /*
359     * b = (t * inv) mod (p-1)
360     * b = (t * inv(k,(p-1),(p-1)) mod (p-1)
361     * b = (((M-x*a) mod (p-1)) * inv(k,(p-1),(p-1))) mod (p-1)
362     *
363     */
364     mpi_sub_ui(p_1, p_1, 1);
365     k = gen_k( skey->p );
366     mpi_powm( a, skey->g, k, skey->p );
367     mpi_mul(t, skey->x, a );
368     mpi_subm(t, input, t, p_1 );
369     while( mpi_is_neg(t) )
370         mpi_add(t, t, p_1);
371     mpi_invm(inv, k, p_1 );
372     mpi_mulm(b, t, inv, p_1 );
373
374   #if 0
375     if( DBG_CIPHER ) {
376         log_mpidump("elg sign p= ", skey->p);
377         log_mpidump("elg sign g= ", skey->g);
378         log_mpidump("elg sign y= ", skey->y);
379         log_mpidump("elg sign x= ", skey->x);
380         log_mpidump("elg sign k= ", k);
381         log_mpidump("elg sign M= ", input);
382         log_mpidump("elg sign a= ", a);
383         log_mpidump("elg sign b= ", b);
384     }
385   #endif
386     mpi_free(k);
387     mpi_free(t);
388     mpi_free(inv);
389     mpi_free(p_1);
390 }
391
392
393 /****************
394  * Returns true if the signature composed of A and B is valid.
395  */
396 static int
397 verify(MPI a, MPI b, MPI input, ELG_public_key *pkey )
398 {
399     int rc;
400     MPI t1;
401     MPI t2;
402     MPI base[4];
403     MPI exp[4];
404
405     if( !(mpi_cmp_ui( a, 0 ) > 0 && mpi_cmp( a, pkey->p ) < 0) )
406         return 0; /* assertion  0 < a < p  failed */
407
408     t1 = mpi_alloc( mpi_get_nlimbs(a) );
409     t2 = mpi_alloc( mpi_get_nlimbs(a) );
410
411   #if 0
412     /* t1 = (y^a mod p) * (a^b mod p) mod p */
413     mpi_powm( t1, pkey->y, a, pkey->p );
414     mpi_powm( t2, a, b, pkey->p );
415     mpi_mulm( t1, t1, t2, pkey->p );
416
417     /* t2 = g ^ input mod p */
418     mpi_powm( t2, pkey->g, input, pkey->p );
419
420     rc = !mpi_cmp( t1, t2 );
421   #elif 0
422     /* t1 = (y^a mod p) * (a^b mod p) mod p */
423     base[0] = pkey->y; exp[0] = a;
424     base[1] = a;       exp[1] = b;
425     base[2] = NULL;    exp[2] = NULL;
426     mpi_mulpowm( t1, base, exp, pkey->p );
427
428     /* t2 = g ^ input mod p */
429     mpi_powm( t2, pkey->g, input, pkey->p );
430
431     rc = !mpi_cmp( t1, t2 );
432   #else
433     /* t1 = g ^ - input * y ^ a * a ^ b  mod p */
434     mpi_invm(t2, pkey->g, pkey->p );
435     base[0] = t2     ; exp[0] = input;
436     base[1] = pkey->y; exp[1] = a;
437     base[2] = a;       exp[2] = b;
438     base[3] = NULL;    exp[3] = NULL;
439     mpi_mulpowm( t1, base, exp, pkey->p );
440     rc = !mpi_cmp_ui( t1, 1 );
441
442   #endif
443
444     mpi_free(t1);
445     mpi_free(t2);
446     return rc;
447 }
448
449 /*********************************************
450  **************  interface  ******************
451  *********************************************/
452
453 int
454 elg_generate( int algo, unsigned nbits, MPI *skey, MPI **retfactors )
455 {
456     ELG_secret_key sk;
457
458     if( !is_ELGAMAL(algo) )
459         return G10ERR_PUBKEY_ALGO;
460
461     generate( &sk, nbits, retfactors );
462     skey[0] = sk.p;
463     skey[1] = sk.g;
464     skey[2] = sk.y;
465     skey[3] = sk.x;
466     return 0;
467 }
468
469
470 int
471 elg_check_secret_key( int algo, MPI *skey )
472 {
473     ELG_secret_key sk;
474
475     if( !is_ELGAMAL(algo) )
476         return G10ERR_PUBKEY_ALGO;
477     if( !skey[0] || !skey[1] || !skey[2] || !skey[3] )
478         return G10ERR_BAD_MPI;
479
480     sk.p = skey[0];
481     sk.g = skey[1];
482     sk.y = skey[2];
483     sk.x = skey[3];
484     if( !check_secret_key( &sk ) )
485         return G10ERR_BAD_SECKEY;
486
487     return 0;
488 }
489
490
491
492 int
493 elg_encrypt( int algo, MPI *resarr, MPI data, MPI *pkey )
494 {
495     ELG_public_key pk;
496
497     if( !is_ELGAMAL(algo) )
498         return G10ERR_PUBKEY_ALGO;
499     if( !data || !pkey[0] || !pkey[1] || !pkey[2] )
500         return G10ERR_BAD_MPI;
501
502     pk.p = pkey[0];
503     pk.g = pkey[1];
504     pk.y = pkey[2];
505     resarr[0] = mpi_alloc( mpi_get_nlimbs( pk.p ) );
506     resarr[1] = mpi_alloc( mpi_get_nlimbs( pk.p ) );
507     encrypt( resarr[0], resarr[1], data, &pk );
508     return 0;
509 }
510
511 int
512 elg_decrypt( int algo, MPI *result, MPI *data, MPI *skey )
513 {
514     ELG_secret_key sk;
515
516     if( !is_ELGAMAL(algo) )
517         return G10ERR_PUBKEY_ALGO;
518     if( !data[0] || !data[1]
519         || !skey[0] || !skey[1] || !skey[2] || !skey[3] )
520         return G10ERR_BAD_MPI;
521
522     sk.p = skey[0];
523     sk.g = skey[1];
524     sk.y = skey[2];
525     sk.x = skey[3];
526     *result = mpi_alloc_secure( mpi_get_nlimbs( sk.p ) );
527     decrypt( *result, data[0], data[1], &sk );
528     return 0;
529 }
530
531 int
532 elg_sign( int algo, MPI *resarr, MPI data, MPI *skey )
533 {
534     ELG_secret_key sk;
535
536     if( !is_ELGAMAL(algo) )
537         return G10ERR_PUBKEY_ALGO;
538     if( !data || !skey[0] || !skey[1] || !skey[2] || !skey[3] )
539         return G10ERR_BAD_MPI;
540
541     sk.p = skey[0];
542     sk.g = skey[1];
543     sk.y = skey[2];
544     sk.x = skey[3];
545     resarr[0] = mpi_alloc( mpi_get_nlimbs( sk.p ) );
546     resarr[1] = mpi_alloc( mpi_get_nlimbs( sk.p ) );
547     sign( resarr[0], resarr[1], data, &sk );
548     return 0;
549 }
550
551 int
552 elg_verify( int algo, MPI hash, MPI *data, MPI *pkey,
553                     int (*cmp)(void *, MPI) UNUSED, void *opaquev UNUSED)
554 {
555     ELG_public_key pk;
556
557     if( !is_ELGAMAL(algo) )
558         return G10ERR_PUBKEY_ALGO;
559     if( !data[0] || !data[1] || !hash
560         || !pkey[0] || !pkey[1] || !pkey[2] )
561         return G10ERR_BAD_MPI;
562
563     pk.p = pkey[0];
564     pk.g = pkey[1];
565     pk.y = pkey[2];
566     if( !verify( data[0], data[1], hash, &pk ) )
567         return G10ERR_BAD_SIGN;
568     return 0;
569 }
570
571
572
573 unsigned
574 elg_get_nbits( int algo, MPI *pkey )
575 {
576     if( !is_ELGAMAL(algo) )
577         return 0;
578     return mpi_get_nbits( pkey[0] );
579 }
580
581
582 /****************
583  * Return some information about the algorithm.  We need algo here to
584  * distinguish different flavors of the algorithm.
585  * Returns: A pointer to string describing the algorithm or NULL if
586  *          the ALGO is invalid.
587  * Usage: Bit 0 set : allows signing
588  *            1 set : allows encryption
589  * NOTE: This function allows signing also for ELG-E, which is not
590  * okay but a bad hack to allow to work with old gpg keys. The real check
591  * is done in the gnupg ocde depending on the packet version.
592  */
593 const char *
594 elg_get_info( int algo, int *npkey, int *nskey, int *nenc, int *nsig,
595                                                          int *use )
596 {
597     *npkey = 3;
598     *nskey = 4;
599     *nenc = 2;
600     *nsig = 2;
601
602     switch( algo ) {
603       case PUBKEY_ALGO_ELGAMAL:
604         *use = PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC;
605         return "ELG";
606       case PUBKEY_ALGO_ELGAMAL_E:
607         *use = PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC;
608         return "ELG-E";
609       default: *use = 0; return NULL;
610     }
611 }
612
613