~darkmuggle-deactivatedaccount/ubuntu/quantal/grub2/fix-872244

« back to all changes in this revision

Viewing changes to grub-core/lib/libgcrypt/cipher/rsa.c

  • Committer: Bazaar Package Importer
  • Author(s): Colin Watson, Colin Watson, Evan Broder, Mario Limonciello
  • Date: 2010-11-24 13:59:55 UTC
  • mfrom: (1.17.6 upstream) (17.6.15 experimental)
  • Revision ID: james.westby@ubuntu.com-20101124135955-r6ii5sepayr7jt53
Tags: 1.99~20101124-1ubuntu1
[ Colin Watson ]
* Resynchronise with Debian experimental.  Remaining changes:
  - Adjust for default Ubuntu boot options ("quiet splash").
  - Default to hiding the menu; holding down Shift at boot will show it.
  - Set a monochromatic theme for Ubuntu.
  - Apply Ubuntu GRUB Legacy changes to legacy update-grub script: title,
    recovery mode, quiet option, tweak how memtest86+ is displayed, and
    use UUIDs where appropriate.
  - Fix backslash-escaping in merge_debconf_into_conf.
  - Remove "GNU/Linux" from default distributor string.
  - Add crashkernel= options if kdump and makedumpfile are available.
  - If other operating systems are installed, then automatically unhide
    the menu.  Otherwise, if GRUB_HIDDEN_TIMEOUT is 0, then use keystatus
    if available to check whether Shift is pressed.  If it is, show the
    menu, otherwise boot immediately.  If keystatus is not available, then
    fall back to a short delay interruptible with Escape.
  - Allow Shift to interrupt 'sleep --interruptible'.
  - Don't display introductory message about line editing unless we're
    actually offering a shell prompt.  Don't clear the screen just before
    booting if we never drew the menu in the first place.
  - Remove some verbose messages printed before reading the configuration
    file.
  - Suppress progress messages as the kernel and initrd load for
    non-recovery kernel menu entries.
  - Change prepare_grub_to_access_device to handle filesystems
    loop-mounted on file images.
  - Ignore devices loop-mounted from files in 10_linux.
  - Show the boot menu if the previous boot failed, that is if it failed
    to get to the end of one of the normal runlevels.
  - Don't generate /boot/grub/device.map during grub-install or
    grub-mkconfig by default.
  - Adjust upgrade version checks for Ubuntu.
  - Don't display "GRUB loading" unless Shift is held down.
  - Adjust versions of grub-doc and grub-legacy-doc conflicts to tolerate
    our backport of the grub-doc split.
  - Fix LVM/RAID probing in the absence of /boot/grub/device.map.
  - Look for .mo files in /usr/share/locale-langpack as well, in
    preference.
  - Make sure GRUB_TIMEOUT isn't quoted unnecessarily.
  - Probe all devices in 'grub-probe --target=drive' if
    /boot/grub/device.map is missing.
  - Build-depend on qemu-kvm rather than qemu-system for grub-pc tests.
  - Use qemu rather than qemu-system-i386.
  - Program vesafb on BIOS systems rather than efifb.
  - Add a grub-rescue-efi-amd64 package containing a rescue CD-ROM image
    for EFI-AMD64.
  - On Wubi, don't ask for an install device, but just update wubildr
    using the diverted grub-install.
  - When embedding the core image in a post-MBR gap, check for and avoid
    sectors matching any of a list of known signatures.
  - Disable video_bochs and video_cirrus on PC BIOS systems, as probing
    PCI space seems to break on some systems.
* Downgrade "ACPI shutdown failed" error to a debug message, since it can
  cause spurious test failures.

[ Evan Broder ]
* Enable lua from grub-extras.
* Incorporate the bitop library into lua.
* Add enum_pci function to grub module in lua.
* Switch back to gfxpayload=keep by default, unless the video hardware
  is known to not support it.

[ Mario Limonciello ]
* Built part_msdos and vfat into bootx64.efi (LP: #677758)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* rsa.c - RSA implementation
 
2
 * Copyright (C) 1997, 1998, 1999 by Werner Koch (dd9jn)
 
3
 * Copyright (C) 2000, 2001, 2002, 2003, 2008 Free Software Foundation, Inc.
 
4
 *
 
5
 * This file is part of Libgcrypt.
 
6
 *
 
7
 * Libgcrypt is free software; you can redistribute it and/or modify
 
8
 * it under the terms of the GNU Lesser General Public License as
 
9
 * published by the Free Software Foundation; either version 2.1 of
 
10
 * the License, or (at your option) any later version.
 
11
 *
 
12
 * Libgcrypt is distributed in the hope that it will be useful,
 
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
15
 * GNU Lesser General Public License for more details.
 
16
 *
 
17
 * You should have received a copy of the GNU Lesser General Public
 
18
 * License along with this program; if not, see <http://www.gnu.org/licenses/>.
 
19
 */
 
20
 
 
21
/* This code uses an algorithm protected by U.S. Patent #4,405,829
 
22
   which expired on September 20, 2000.  The patent holder placed that
 
23
   patent into the public domain on Sep 6th, 2000.
 
24
*/
 
25
 
 
26
#include <config.h>
 
27
#include <stdio.h>
 
28
#include <stdlib.h>
 
29
#include <string.h>
 
30
#include <errno.h>
 
31
 
 
32
#include "g10lib.h"
 
33
#include "mpi.h"
 
34
#include "cipher.h"
 
35
 
 
36
 
 
37
typedef struct
 
38
{
 
39
  gcry_mpi_t n;     /* modulus */
 
40
  gcry_mpi_t e;     /* exponent */
 
41
} RSA_public_key;
 
42
 
 
43
 
 
44
typedef struct
 
45
{
 
46
  gcry_mpi_t n;     /* public modulus */
 
47
  gcry_mpi_t e;     /* public exponent */
 
48
  gcry_mpi_t d;     /* exponent */
 
49
  gcry_mpi_t p;     /* prime  p. */
 
50
  gcry_mpi_t q;     /* prime  q. */
 
51
  gcry_mpi_t u;     /* inverse of p mod q. */
 
52
} RSA_secret_key;
 
53
 
 
54
 
 
55
/* A sample 1024 bit RSA key used for the selftests.  */
 
56
static const char sample_secret_key[] =
 
57
"(private-key"
 
58
" (rsa"
 
59
"  (n #00e0ce96f90b6c9e02f3922beada93fe50a875eac6bcc18bb9a9cf2e84965caa"
 
60
"      2d1ff95a7f542465c6c0c19d276e4526ce048868a7a914fd343cc3a87dd74291"
 
61
"      ffc565506d5bbb25cbac6a0e2dd1f8bcaab0d4a29c2f37c950f363484bf269f7"
 
62
"      891440464baf79827e03a36e70b814938eebdc63e964247be75dc58b014b7ea251#)"
 
63
"  (e #010001#)"
 
64
"  (d #046129f2489d71579be0a75fe029bd6cdb574ebf57ea8a5b0fda942cab943b11"
 
65
"      7d7bb95e5d28875e0f9fc5fcc06a72f6d502464dabded78ef6b716177b83d5bd"
 
66
"      c543dc5d3fed932e59f5897e92e6f58a0f33424106a3b6fa2cbf877510e4ac21"
 
67
"      c3ee47851e97d12996222ac3566d4ccb0b83d164074abf7de655fc2446da1781#)"
 
68
"  (p #00e861b700e17e8afe6837e7512e35b6ca11d0ae47d8b85161c67baf64377213"
 
69
"      fe52d772f2035b3ca830af41d8a4120e1c1c70d12cc22f00d28d31dd48a8d424f1#)"
 
70
"  (q #00f7a7ca5367c661f8e62df34f0d05c10c88e5492348dd7bddc942c9a8f369f9"
 
71
"      35a07785d2db805215ed786e4285df1658eed3ce84f469b81b50d358407b4ad361#)"
 
72
"  (u #304559a9ead56d2309d203811a641bb1a09626bc8eb36fffa23c968ec5bd891e"
 
73
"      ebbafc73ae666e01ba7c8990bae06cc2bbe10b75e69fcacb353a6473079d8e9b#)))";
 
74
/* A sample 1024 bit RSA key used for the selftests (public only).  */
 
75
static const char sample_public_key[] = 
 
76
"(public-key"
 
77
" (rsa"
 
78
"  (n #00e0ce96f90b6c9e02f3922beada93fe50a875eac6bcc18bb9a9cf2e84965caa"
 
79
"      2d1ff95a7f542465c6c0c19d276e4526ce048868a7a914fd343cc3a87dd74291"
 
80
"      ffc565506d5bbb25cbac6a0e2dd1f8bcaab0d4a29c2f37c950f363484bf269f7"
 
81
"      891440464baf79827e03a36e70b814938eebdc63e964247be75dc58b014b7ea251#)"
 
82
"  (e #010001#)))";
 
83
 
 
84
 
 
85
 
 
86
 
 
87
static int test_keys (RSA_secret_key *sk, unsigned nbits);
 
88
static int  check_secret_key (RSA_secret_key *sk);
 
89
static void public (gcry_mpi_t output, gcry_mpi_t input, RSA_public_key *skey);
 
90
static void secret (gcry_mpi_t output, gcry_mpi_t input, RSA_secret_key *skey);
 
91
 
 
92
 
 
93
/* Check that a freshly generated key actually works.  Returns 0 on success. */
 
94
static int
 
95
test_keys (RSA_secret_key *sk, unsigned int nbits)
 
96
{
 
97
  int result = -1; /* Default to failure.  */
 
98
  RSA_public_key pk;
 
99
  gcry_mpi_t plaintext = gcry_mpi_new (nbits);
 
100
  gcry_mpi_t ciphertext = gcry_mpi_new (nbits);
 
101
  gcry_mpi_t decr_plaintext = gcry_mpi_new (nbits);
 
102
  gcry_mpi_t signature = gcry_mpi_new (nbits);
 
103
 
 
104
  /* Put the relevant parameters into a public key structure.  */
 
105
  pk.n = sk->n;
 
106
  pk.e = sk->e;
 
107
 
 
108
  /* Create a random plaintext.  */
 
109
  gcry_mpi_randomize (plaintext, nbits, GCRY_WEAK_RANDOM);
 
110
 
 
111
  /* Encrypt using the public key.  */
 
112
  public (ciphertext, plaintext, &pk);
 
113
 
 
114
  /* Check that the cipher text does not match the plaintext.  */
 
115
  if (!gcry_mpi_cmp (ciphertext, plaintext))
 
116
    goto leave; /* Ciphertext is identical to the plaintext.  */
 
117
 
 
118
  /* Decrypt using the secret key.  */
 
119
  secret (decr_plaintext, ciphertext, sk);
 
120
 
 
121
  /* Check that the decrypted plaintext matches the original plaintext.  */
 
122
  if (gcry_mpi_cmp (decr_plaintext, plaintext))
 
123
    goto leave; /* Plaintext does not match.  */
 
124
 
 
125
  /* Create another random plaintext as data for signature checking.  */
 
126
  gcry_mpi_randomize (plaintext, nbits, GCRY_WEAK_RANDOM);
 
127
 
 
128
  /* Use the RSA secret function to create a signature of the plaintext.  */
 
129
  secret (signature, plaintext, sk);
 
130
  
 
131
  /* Use the RSA public function to verify this signature.  */
 
132
  public (decr_plaintext, signature, &pk);
 
133
  if (gcry_mpi_cmp (decr_plaintext, plaintext))
 
134
    goto leave; /* Signature does not match.  */
 
135
 
 
136
  /* Modify the signature and check that the signing fails.  */
 
137
  gcry_mpi_add_ui (signature, signature, 1);
 
138
  public (decr_plaintext, signature, &pk);
 
139
  if (!gcry_mpi_cmp (decr_plaintext, plaintext))
 
140
    goto leave; /* Signature matches but should not.  */
 
141
 
 
142
  result = 0; /* All tests succeeded.  */
 
143
 
 
144
 leave:
 
145
  gcry_mpi_release (signature);
 
146
  gcry_mpi_release (decr_plaintext);
 
147
  gcry_mpi_release (ciphertext);
 
148
  gcry_mpi_release (plaintext);
 
149
  return result;
 
150
}
 
151
 
 
152
 
 
153
/* Callback used by the prime generation to test whether the exponent
 
154
   is suitable. Returns 0 if the test has been passed. */
 
155
static int
 
156
check_exponent (void *arg, gcry_mpi_t a)
 
157
{
 
158
  gcry_mpi_t e = arg;
 
159
  gcry_mpi_t tmp;
 
160
  int result;
 
161
  
 
162
  mpi_sub_ui (a, a, 1);
 
163
  tmp = _gcry_mpi_alloc_like (a);
 
164
  result = !gcry_mpi_gcd(tmp, e, a); /* GCD is not 1. */
 
165
  gcry_mpi_release (tmp);
 
166
  mpi_add_ui (a, a, 1);
 
167
  return result;
 
168
}
 
169
 
 
170
/****************
 
171
 * Generate a key pair with a key of size NBITS.  
 
172
 * USE_E = 0 let Libcgrypt decide what exponent to use.
 
173
 *       = 1 request the use of a "secure" exponent; this is required by some 
 
174
 *           specification to be 65537.
 
175
 *       > 2 Use this public exponent.  If the given exponent
 
176
 *           is not odd one is internally added to it. 
 
177
 * TRANSIENT_KEY:  If true, generate the primes using the standard RNG.
 
178
 * Returns: 2 structures filled with all needed values
 
179
 */
 
180
static gpg_err_code_t
 
181
generate_std (RSA_secret_key *sk, unsigned int nbits, unsigned long use_e,
 
182
              int transient_key)
 
183
{
 
184
  gcry_mpi_t p, q; /* the two primes */
 
185
  gcry_mpi_t d;    /* the private key */
 
186
  gcry_mpi_t u;
 
187
  gcry_mpi_t t1, t2;
 
188
  gcry_mpi_t n;    /* the public key */
 
189
  gcry_mpi_t e;    /* the exponent */
 
190
  gcry_mpi_t phi;  /* helper: (p-1)(q-1) */
 
191
  gcry_mpi_t g;
 
192
  gcry_mpi_t f;
 
193
  gcry_random_level_t random_level;
 
194
 
 
195
  if (fips_mode ())
 
196
    {
 
197
      if (nbits < 1024)
 
198
        return GPG_ERR_INV_VALUE;
 
199
      if (transient_key)
 
200
        return GPG_ERR_INV_VALUE;
 
201
    }
 
202
 
 
203
  /* The random quality depends on the transient_key flag.  */
 
204
  random_level = transient_key ? GCRY_STRONG_RANDOM : GCRY_VERY_STRONG_RANDOM;
 
205
 
 
206
  /* Make sure that nbits is even so that we generate p, q of equal size. */
 
207
  if ( (nbits&1) )
 
208
    nbits++; 
 
209
 
 
210
  if (use_e == 1)   /* Alias for a secure value */
 
211
    use_e = 65537;  /* as demanded by Sphinx. */
 
212
 
 
213
  /* Public exponent:
 
214
     In general we use 41 as this is quite fast and more secure than the
 
215
     commonly used 17.  Benchmarking the RSA verify function
 
216
     with a 1024 bit key yields (2001-11-08): 
 
217
     e=17    0.54 ms
 
218
     e=41    0.75 ms
 
219
     e=257   0.95 ms
 
220
     e=65537 1.80 ms
 
221
  */
 
222
  e = mpi_alloc( (32+BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB );
 
223
  if (!use_e)
 
224
    mpi_set_ui (e, 41);     /* This is a reasonable secure and fast value */
 
225
  else 
 
226
    {
 
227
      use_e |= 1; /* make sure this is odd */
 
228
      mpi_set_ui (e, use_e); 
 
229
    }
 
230
    
 
231
  n = gcry_mpi_new (nbits);
 
232
 
 
233
  p = q = NULL;
 
234
  do
 
235
    {
 
236
      /* select two (very secret) primes */
 
237
      if (p)
 
238
        gcry_mpi_release (p);
 
239
      if (q)
 
240
        gcry_mpi_release (q);
 
241
      if (use_e)
 
242
        { /* Do an extra test to ensure that the given exponent is
 
243
             suitable. */
 
244
          p = _gcry_generate_secret_prime (nbits/2, random_level,
 
245
                                           check_exponent, e);
 
246
          q = _gcry_generate_secret_prime (nbits/2, random_level,
 
247
                                           check_exponent, e);
 
248
        }
 
249
      else
 
250
        { /* We check the exponent later. */
 
251
          p = _gcry_generate_secret_prime (nbits/2, random_level, NULL, NULL);
 
252
          q = _gcry_generate_secret_prime (nbits/2, random_level, NULL, NULL);
 
253
        }
 
254
      if (mpi_cmp (p, q) > 0 ) /* p shall be smaller than q (for calc of u)*/
 
255
        mpi_swap(p,q);
 
256
      /* calculate the modulus */
 
257
      mpi_mul( n, p, q );
 
258
    }
 
259
  while ( mpi_get_nbits(n) != nbits );
 
260
 
 
261
  /* calculate Euler totient: phi = (p-1)(q-1) */
 
262
  t1 = mpi_alloc_secure( mpi_get_nlimbs(p) );
 
263
  t2 = mpi_alloc_secure( mpi_get_nlimbs(p) );
 
264
  phi = gcry_mpi_snew ( nbits );
 
265
  g     = gcry_mpi_snew ( nbits );
 
266
  f     = gcry_mpi_snew ( nbits );
 
267
  mpi_sub_ui( t1, p, 1 );
 
268
  mpi_sub_ui( t2, q, 1 );
 
269
  mpi_mul( phi, t1, t2 );
 
270
  gcry_mpi_gcd(g, t1, t2);
 
271
  mpi_fdiv_q(f, phi, g);
 
272
 
 
273
  while (!gcry_mpi_gcd(t1, e, phi)) /* (while gcd is not 1) */
 
274
    {
 
275
      if (use_e)
 
276
        BUG (); /* The prime generator already made sure that we
 
277
                   never can get to here. */
 
278
      mpi_add_ui (e, e, 2);
 
279
    }
 
280
 
 
281
  /* calculate the secret key d = e^1 mod phi */
 
282
  d = gcry_mpi_snew ( nbits );
 
283
  mpi_invm(d, e, f );
 
284
  /* calculate the inverse of p and q (used for chinese remainder theorem)*/
 
285
  u = gcry_mpi_snew ( nbits );
 
286
  mpi_invm(u, p, q );
 
287
 
 
288
  if( DBG_CIPHER )
 
289
    {
 
290
      log_mpidump("  p= ", p );
 
291
      log_mpidump("  q= ", q );
 
292
      log_mpidump("phi= ", phi );
 
293
      log_mpidump("  g= ", g );
 
294
      log_mpidump("  f= ", f );
 
295
      log_mpidump("  n= ", n );
 
296
      log_mpidump("  e= ", e );
 
297
      log_mpidump("  d= ", d );
 
298
      log_mpidump("  u= ", u );
 
299
    }
 
300
 
 
301
  gcry_mpi_release (t1);
 
302
  gcry_mpi_release (t2);
 
303
  gcry_mpi_release (phi);
 
304
  gcry_mpi_release (f);
 
305
  gcry_mpi_release (g);
 
306
 
 
307
  sk->n = n;
 
308
  sk->e = e;
 
309
  sk->p = p;
 
310
  sk->q = q;
 
311
  sk->d = d;
 
312
  sk->u = u;
 
313
 
 
314
  /* Now we can test our keys. */
 
315
  if (test_keys (sk, nbits - 64))
 
316
    {
 
317
      gcry_mpi_release (sk->n); sk->n = NULL;
 
318
      gcry_mpi_release (sk->e); sk->e = NULL;
 
319
      gcry_mpi_release (sk->p); sk->p = NULL;
 
320
      gcry_mpi_release (sk->q); sk->q = NULL;
 
321
      gcry_mpi_release (sk->d); sk->d = NULL;
 
322
      gcry_mpi_release (sk->u); sk->u = NULL;
 
323
      fips_signal_error ("self-test after key generation failed");
 
324
      return GPG_ERR_SELFTEST_FAILED;
 
325
    }
 
326
 
 
327
  return 0;
 
328
}
 
329
 
 
330
 
 
331
/* Helper for generate_x931.  */
 
332
static gcry_mpi_t 
 
333
gen_x931_parm_xp (unsigned int nbits)
 
334
{
 
335
  gcry_mpi_t xp;
 
336
 
 
337
  xp = gcry_mpi_snew (nbits);
 
338
  gcry_mpi_randomize (xp, nbits, GCRY_VERY_STRONG_RANDOM);
 
339
      
 
340
  /* The requirement for Xp is:
 
341
 
 
342
       sqrt{2}*2^{nbits-1} <= xp <= 2^{nbits} - 1
 
343
 
 
344
     We set the two high order bits to 1 to satisfy the lower bound.
 
345
     By using mpi_set_highbit we make sure that the upper bound is
 
346
     satisfied as well.  */
 
347
  mpi_set_highbit (xp, nbits-1);
 
348
  mpi_set_bit (xp, nbits-2);
 
349
  gcry_assert ( mpi_get_nbits (xp) == nbits );
 
350
  
 
351
  return xp;
 
352
}     
 
353
 
 
354
 
 
355
/* Helper for generate_x931.  */
 
356
static gcry_mpi_t 
 
357
gen_x931_parm_xi (void)
 
358
{
 
359
  gcry_mpi_t xi;
 
360
 
 
361
  xi = gcry_mpi_snew (101);
 
362
  gcry_mpi_randomize (xi, 101, GCRY_VERY_STRONG_RANDOM);
 
363
  mpi_set_highbit (xi, 100);
 
364
  gcry_assert ( mpi_get_nbits (xi) == 101 );
 
365
  
 
366
  return xi;
 
367
}     
 
368
 
 
369
 
 
370
 
 
371
/* Variant of the standard key generation code using the algorithm
 
372
   from X9.31.  Using this algorithm has the advantage that the
 
373
   generation can be made deterministic which is required for CAVS
 
374
   testing.  */
 
375
static gpg_err_code_t
 
376
generate_x931 (RSA_secret_key *sk, unsigned int nbits, unsigned long e_value,
 
377
               gcry_sexp_t deriveparms, int *swapped)
 
378
{
 
379
  gcry_mpi_t p, q; /* The two primes.  */
 
380
  gcry_mpi_t e;    /* The public exponent.  */
 
381
  gcry_mpi_t n;    /* The public key.  */
 
382
  gcry_mpi_t d;    /* The private key */
 
383
  gcry_mpi_t u;    /* The inverse of p and q.  */
 
384
  gcry_mpi_t pm1;  /* p - 1  */
 
385
  gcry_mpi_t qm1;  /* q - 1  */
 
386
  gcry_mpi_t phi;  /* Euler totient.  */
 
387
  gcry_mpi_t f, g; /* Helper.  */
 
388
 
 
389
  *swapped = 0;
 
390
 
 
391
  if (e_value == 1)   /* Alias for a secure value. */
 
392
    e_value = 65537; 
 
393
 
 
394
  /* Point 1 of section 4.1:  k = 1024 + 256s with S >= 0  */
 
395
  if (nbits < 1024 || (nbits % 256))
 
396
    return GPG_ERR_INV_VALUE;
 
397
  
 
398
  /* Point 2:  2 <= bitlength(e) < 2^{k-2}
 
399
     Note that we do not need to check the upper bound because we use
 
400
     an unsigned long for E and thus there is no way for E to reach
 
401
     that limit.  */
 
402
  if (e_value < 3)
 
403
    return GPG_ERR_INV_VALUE;
 
404
     
 
405
  /* Our implementaion requires E to be odd.  */
 
406
  if (!(e_value & 1))
 
407
    return GPG_ERR_INV_VALUE;
 
408
 
 
409
  /* Point 3:  e > 0 or e 0 if it is to be randomly generated.
 
410
     We support only a fixed E and thus there is no need for an extra test.  */
 
411
 
 
412
 
 
413
  /* Compute or extract the derive parameters.  */
 
414
  {
 
415
    gcry_mpi_t xp1 = NULL;
 
416
    gcry_mpi_t xp2 = NULL;
 
417
    gcry_mpi_t xp  = NULL;
 
418
    gcry_mpi_t xq1 = NULL;
 
419
    gcry_mpi_t xq2 = NULL;
 
420
    gcry_mpi_t xq  = NULL;
 
421
    gcry_mpi_t tmpval;
 
422
 
 
423
    if (!deriveparms)
 
424
      {
 
425
        /* Not given: Generate them.  */
 
426
        xp = gen_x931_parm_xp (nbits/2);
 
427
        /* Make sure that |xp - xq| > 2^{nbits - 100} holds.  */
 
428
        tmpval = gcry_mpi_snew (nbits/2);
 
429
        do
 
430
          {
 
431
            gcry_mpi_release (xq);
 
432
            xq = gen_x931_parm_xp (nbits/2);
 
433
            mpi_sub (tmpval, xp, xq);
 
434
          }
 
435
        while (mpi_get_nbits (tmpval) <= (nbits/2 - 100));
 
436
        gcry_mpi_release (tmpval);
 
437
 
 
438
        xp1 = gen_x931_parm_xi ();
 
439
        xp2 = gen_x931_parm_xi ();
 
440
        xq1 = gen_x931_parm_xi ();
 
441
        xq2 = gen_x931_parm_xi ();
 
442
 
 
443
      }
 
444
    else
 
445
      {
 
446
        /* Parameters to derive the key are given.  */
 
447
        struct { const char *name; gcry_mpi_t *value; } tbl[] = {
 
448
          { "Xp1", &xp1 },
 
449
          { "Xp2", &xp2 },
 
450
          { "Xp",  &xp  },
 
451
          { "Xq1", &xq1 },
 
452
          { "Xq2", &xq2 },
 
453
          { "Xq",  &xq  },
 
454
          { NULL,  NULL }
 
455
        };
 
456
        int idx;
 
457
        gcry_sexp_t oneparm;
 
458
        
 
459
        for (idx=0; tbl[idx].name; idx++)
 
460
          {
 
461
            oneparm = gcry_sexp_find_token (deriveparms, tbl[idx].name, 0);
 
462
            if (oneparm)
 
463
              {
 
464
                *tbl[idx].value = gcry_sexp_nth_mpi (oneparm, 1,
 
465
                                                     GCRYMPI_FMT_USG);
 
466
                gcry_sexp_release (oneparm);
 
467
              }
 
468
          }
 
469
        for (idx=0; tbl[idx].name; idx++)
 
470
          if (!*tbl[idx].value)
 
471
            break;
 
472
        if (tbl[idx].name)
 
473
          {
 
474
            /* At least one parameter is missing.  */
 
475
            for (idx=0; tbl[idx].name; idx++)
 
476
              gcry_mpi_release (*tbl[idx].value);
 
477
            return GPG_ERR_MISSING_VALUE;
 
478
          }
 
479
      }
 
480
    
 
481
    e = mpi_alloc_set_ui (e_value); 
 
482
 
 
483
    /* Find two prime numbers.  */
 
484
    p = _gcry_derive_x931_prime (xp, xp1, xp2, e, NULL, NULL);
 
485
    q = _gcry_derive_x931_prime (xq, xq1, xq2, e, NULL, NULL);
 
486
    gcry_mpi_release (xp);  xp  = NULL;
 
487
    gcry_mpi_release (xp1); xp1 = NULL;
 
488
    gcry_mpi_release (xp2); xp2 = NULL;
 
489
    gcry_mpi_release (xq);  xq  = NULL; 
 
490
    gcry_mpi_release (xq1); xq1 = NULL;
 
491
    gcry_mpi_release (xq2); xq2 = NULL;
 
492
    if (!p || !q)
 
493
      {
 
494
        gcry_mpi_release (p);
 
495
        gcry_mpi_release (q);
 
496
        gcry_mpi_release (e);
 
497
        return GPG_ERR_NO_PRIME;
 
498
      }
 
499
  }
 
500
 
 
501
 
 
502
  /* Compute the public modulus.  We make sure that p is smaller than
 
503
     q to allow the use of the CRT.  */
 
504
  if (mpi_cmp (p, q) > 0 )
 
505
    {
 
506
      mpi_swap (p, q);
 
507
      *swapped = 1;
 
508
    }
 
509
  n = gcry_mpi_new (nbits);
 
510
  mpi_mul (n, p, q);
 
511
 
 
512
  /* Compute the Euler totient:  phi = (p-1)(q-1)  */
 
513
  pm1 = gcry_mpi_snew (nbits/2);
 
514
  qm1 = gcry_mpi_snew (nbits/2);
 
515
  phi = gcry_mpi_snew (nbits);
 
516
  mpi_sub_ui (pm1, p, 1);
 
517
  mpi_sub_ui (qm1, q, 1);
 
518
  mpi_mul (phi, pm1, qm1);
 
519
 
 
520
  g = gcry_mpi_snew (nbits);
 
521
  gcry_assert (gcry_mpi_gcd (g, e, phi));
 
522
 
 
523
  /* Compute: f = lcm(p-1,q-1) = phi / gcd(p-1,q-1) */
 
524
  gcry_mpi_gcd (g, pm1, qm1);
 
525
  f = pm1; pm1 = NULL;
 
526
  gcry_mpi_release (qm1); qm1 = NULL;
 
527
  mpi_fdiv_q (f, phi, g);
 
528
  gcry_mpi_release (phi); phi = NULL;
 
529
  d = g; g = NULL;
 
530
  /* Compute the secret key:  d = e^{-1} mod lcm(p-1,q-1) */
 
531
  mpi_invm (d, e, f);
 
532
 
 
533
  /* Compute the inverse of p and q.  */
 
534
  u = f; f = NULL;
 
535
  mpi_invm (u, p, q );
 
536
 
 
537
  if( DBG_CIPHER )
 
538
    {
 
539
      if (*swapped)
 
540
        log_debug ("p and q are swapped\n");
 
541
      log_mpidump("  p", p );
 
542
      log_mpidump("  q", q );
 
543
      log_mpidump("  n", n );
 
544
      log_mpidump("  e", e );
 
545
      log_mpidump("  d", d );
 
546
      log_mpidump("  u", u );
 
547
    }
 
548
 
 
549
 
 
550
  sk->n = n;
 
551
  sk->e = e;
 
552
  sk->p = p;
 
553
  sk->q = q;
 
554
  sk->d = d;
 
555
  sk->u = u;
 
556
 
 
557
  /* Now we can test our keys. */
 
558
  if (test_keys (sk, nbits - 64))
 
559
    {
 
560
      gcry_mpi_release (sk->n); sk->n = NULL;
 
561
      gcry_mpi_release (sk->e); sk->e = NULL;
 
562
      gcry_mpi_release (sk->p); sk->p = NULL;
 
563
      gcry_mpi_release (sk->q); sk->q = NULL;
 
564
      gcry_mpi_release (sk->d); sk->d = NULL;
 
565
      gcry_mpi_release (sk->u); sk->u = NULL;
 
566
      fips_signal_error ("self-test after key generation failed");
 
567
      return GPG_ERR_SELFTEST_FAILED;
 
568
    }
 
569
 
 
570
  return 0;
 
571
}
 
572
 
 
573
 
 
574
/****************
 
575
 * Test wether the secret key is valid.
 
576
 * Returns: true if this is a valid key.
 
577
 */
 
578
static int
 
579
check_secret_key( RSA_secret_key *sk )
 
580
{
 
581
  int rc;
 
582
  gcry_mpi_t temp = mpi_alloc( mpi_get_nlimbs(sk->p)*2 );
 
583
  
 
584
  mpi_mul(temp, sk->p, sk->q );
 
585
  rc = mpi_cmp( temp, sk->n );
 
586
  mpi_free(temp);
 
587
  return !rc;
 
588
}
 
589
 
 
590
 
 
591
 
 
592
/****************
 
593
 * Public key operation. Encrypt INPUT with PKEY and put result into OUTPUT.
 
594
 *
 
595
 *      c = m^e mod n
 
596
 *
 
597
 * Where c is OUTPUT, m is INPUT and e,n are elements of PKEY.
 
598
 */
 
599
static void
 
600
public(gcry_mpi_t output, gcry_mpi_t input, RSA_public_key *pkey )
 
601
{
 
602
  if( output == input )  /* powm doesn't like output and input the same */
 
603
    {
 
604
      gcry_mpi_t x = mpi_alloc( mpi_get_nlimbs(input)*2 );
 
605
      mpi_powm( x, input, pkey->e, pkey->n );
 
606
      mpi_set(output, x);
 
607
      mpi_free(x);
 
608
    }
 
609
  else
 
610
    mpi_powm( output, input, pkey->e, pkey->n );
 
611
}
 
612
 
 
613
#if 0
 
614
static void
 
615
stronger_key_check ( RSA_secret_key *skey )
 
616
{
 
617
  gcry_mpi_t t = mpi_alloc_secure ( 0 );
 
618
  gcry_mpi_t t1 = mpi_alloc_secure ( 0 );
 
619
  gcry_mpi_t t2 = mpi_alloc_secure ( 0 );
 
620
  gcry_mpi_t phi = mpi_alloc_secure ( 0 );
 
621
 
 
622
  /* check that n == p * q */
 
623
  mpi_mul( t, skey->p, skey->q);
 
624
  if (mpi_cmp( t, skey->n) )
 
625
    log_info ( "RSA Oops: n != p * q\n" );
 
626
 
 
627
  /* check that p is less than q */
 
628
  if( mpi_cmp( skey->p, skey->q ) > 0 )
 
629
    {
 
630
      log_info ("RSA Oops: p >= q - fixed\n");
 
631
      _gcry_mpi_swap ( skey->p, skey->q);
 
632
    }
 
633
 
 
634
    /* check that e divides neither p-1 nor q-1 */
 
635
    mpi_sub_ui(t, skey->p, 1 );
 
636
    mpi_fdiv_r(t, t, skey->e );
 
637
    if ( !mpi_cmp_ui( t, 0) )
 
638
        log_info ( "RSA Oops: e divides p-1\n" );
 
639
    mpi_sub_ui(t, skey->q, 1 );
 
640
    mpi_fdiv_r(t, t, skey->e );
 
641
    if ( !mpi_cmp_ui( t, 0) )
 
642
        log_info ( "RSA Oops: e divides q-1\n" );
 
643
 
 
644
    /* check that d is correct */
 
645
    mpi_sub_ui( t1, skey->p, 1 );
 
646
    mpi_sub_ui( t2, skey->q, 1 );
 
647
    mpi_mul( phi, t1, t2 );
 
648
    gcry_mpi_gcd(t, t1, t2);
 
649
    mpi_fdiv_q(t, phi, t);
 
650
    mpi_invm(t, skey->e, t );
 
651
    if ( mpi_cmp(t, skey->d ) )
 
652
      {
 
653
        log_info ( "RSA Oops: d is wrong - fixed\n");
 
654
        mpi_set (skey->d, t);
 
655
        _gcry_log_mpidump ("  fixed d", skey->d);
 
656
      }
 
657
 
 
658
    /* check for correctness of u */
 
659
    mpi_invm(t, skey->p, skey->q );
 
660
    if ( mpi_cmp(t, skey->u ) )
 
661
      {
 
662
        log_info ( "RSA Oops: u is wrong - fixed\n");
 
663
        mpi_set (skey->u, t);
 
664
        _gcry_log_mpidump ("  fixed u", skey->u);
 
665
      }
 
666
 
 
667
    log_info ( "RSA secret key check finished\n");
 
668
 
 
669
    mpi_free (t);
 
670
    mpi_free (t1);
 
671
    mpi_free (t2);
 
672
    mpi_free (phi);
 
673
}
 
674
#endif
 
675
 
 
676
 
 
677
 
 
678
/****************
 
679
 * Secret key operation. Encrypt INPUT with SKEY and put result into OUTPUT.
 
680
 *
 
681
 *      m = c^d mod n
 
682
 *
 
683
 * Or faster:
 
684
 *
 
685
 *      m1 = c ^ (d mod (p-1)) mod p 
 
686
 *      m2 = c ^ (d mod (q-1)) mod q 
 
687
 *      h = u * (m2 - m1) mod q 
 
688
 *      m = m1 + h * p
 
689
 *
 
690
 * Where m is OUTPUT, c is INPUT and d,n,p,q,u are elements of SKEY.
 
691
 */
 
692
static void
 
693
secret(gcry_mpi_t output, gcry_mpi_t input, RSA_secret_key *skey )
 
694
{
 
695
  if (!skey->p || !skey->q || !skey->u)
 
696
    {
 
697
      mpi_powm (output, input, skey->d, skey->n);
 
698
    }
 
699
  else
 
700
    {
 
701
      gcry_mpi_t m1 = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );
 
702
      gcry_mpi_t m2 = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );
 
703
      gcry_mpi_t h  = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );
 
704
      
 
705
      /* m1 = c ^ (d mod (p-1)) mod p */
 
706
      mpi_sub_ui( h, skey->p, 1  );
 
707
      mpi_fdiv_r( h, skey->d, h );   
 
708
      mpi_powm( m1, input, h, skey->p );
 
709
      /* m2 = c ^ (d mod (q-1)) mod q */
 
710
      mpi_sub_ui( h, skey->q, 1  );
 
711
      mpi_fdiv_r( h, skey->d, h );
 
712
      mpi_powm( m2, input, h, skey->q );
 
713
      /* h = u * ( m2 - m1 ) mod q */
 
714
      mpi_sub( h, m2, m1 );
 
715
      if ( mpi_is_neg( h ) ) 
 
716
        mpi_add ( h, h, skey->q );
 
717
      mpi_mulm( h, skey->u, h, skey->q ); 
 
718
      /* m = m2 + h * p */
 
719
      mpi_mul ( h, h, skey->p );
 
720
      mpi_add ( output, m1, h );
 
721
    
 
722
      mpi_free ( h );
 
723
      mpi_free ( m1 );
 
724
      mpi_free ( m2 );
 
725
    }
 
726
}
 
727
 
 
728
 
 
729
 
 
730
/* Perform RSA blinding.  */
 
731
static gcry_mpi_t
 
732
rsa_blind (gcry_mpi_t x, gcry_mpi_t r, gcry_mpi_t e, gcry_mpi_t n)
 
733
{
 
734
  /* A helper.  */
 
735
  gcry_mpi_t a;
 
736
 
 
737
  /* Result.  */
 
738
  gcry_mpi_t y;
 
739
 
 
740
  a = gcry_mpi_snew (gcry_mpi_get_nbits (n));
 
741
  y = gcry_mpi_snew (gcry_mpi_get_nbits (n));
 
742
  
 
743
  /* Now we calculate: y = (x * r^e) mod n, where r is the random
 
744
     number, e is the public exponent, x is the non-blinded data and n
 
745
     is the RSA modulus.  */
 
746
  gcry_mpi_powm (a, r, e, n);
 
747
  gcry_mpi_mulm (y, a, x, n);
 
748
 
 
749
  gcry_mpi_release (a);
 
750
 
 
751
  return y;
 
752
}
 
753
 
 
754
/* Undo RSA blinding.  */
 
755
static gcry_mpi_t
 
756
rsa_unblind (gcry_mpi_t x, gcry_mpi_t ri, gcry_mpi_t n)
 
757
{
 
758
  gcry_mpi_t y;
 
759
 
 
760
  y = gcry_mpi_snew (gcry_mpi_get_nbits (n));
 
761
 
 
762
  /* Here we calculate: y = (x * r^-1) mod n, where x is the blinded
 
763
     decrypted data, ri is the modular multiplicative inverse of r and
 
764
     n is the RSA modulus.  */
 
765
 
 
766
  gcry_mpi_mulm (y, ri, x, n);
 
767
 
 
768
  return y;
 
769
}
 
770
 
 
771
/*********************************************
 
772
 **************  interface  ******************
 
773
 *********************************************/
 
774
 
 
775
static gcry_err_code_t
 
776
rsa_generate_ext (int algo, unsigned int nbits, unsigned long evalue,
 
777
                  const gcry_sexp_t genparms,
 
778
                  gcry_mpi_t *skey, gcry_mpi_t **retfactors,
 
779
                  gcry_sexp_t *r_extrainfo)
 
780
{
 
781
  RSA_secret_key sk;
 
782
  gpg_err_code_t ec;
 
783
  gcry_sexp_t deriveparms;
 
784
  int transient_key = 0;
 
785
  int use_x931 = 0;
 
786
  gcry_sexp_t l1;
 
787
 
 
788
  (void)algo;
 
789
  
 
790
  *retfactors = NULL; /* We don't return them.  */
 
791
 
 
792
  deriveparms = (genparms?
 
793
                 gcry_sexp_find_token (genparms, "derive-parms", 0) : NULL);
 
794
  if (!deriveparms)
 
795
    {
 
796
      /* Parse the optional "use-x931" flag. */
 
797
      l1 = gcry_sexp_find_token (genparms, "use-x931", 0);
 
798
      if (l1)
 
799
        {
 
800
          use_x931 = 1;
 
801
          gcry_sexp_release (l1);
 
802
        }
 
803
    }
 
804
 
 
805
  if (deriveparms || use_x931 || fips_mode ())
 
806
    {
 
807
      int swapped;
 
808
      ec = generate_x931 (&sk, nbits, evalue, deriveparms, &swapped);
 
809
      gcry_sexp_release (deriveparms);
 
810
      if (!ec && r_extrainfo && swapped)
 
811
        {
 
812
          ec = gcry_sexp_new (r_extrainfo, 
 
813
                              "(misc-key-info(p-q-swapped))", 0, 1);
 
814
          if (ec)
 
815
            {
 
816
              gcry_mpi_release (sk.n); sk.n = NULL;
 
817
              gcry_mpi_release (sk.e); sk.e = NULL;
 
818
              gcry_mpi_release (sk.p); sk.p = NULL;
 
819
              gcry_mpi_release (sk.q); sk.q = NULL;
 
820
              gcry_mpi_release (sk.d); sk.d = NULL;
 
821
              gcry_mpi_release (sk.u); sk.u = NULL;
 
822
            }
 
823
        }
 
824
    }
 
825
  else
 
826
    {
 
827
      /* Parse the optional "transient-key" flag. */
 
828
      l1 = gcry_sexp_find_token (genparms, "transient-key", 0);
 
829
      if (l1)
 
830
        {
 
831
          transient_key = 1;
 
832
          gcry_sexp_release (l1);
 
833
        }
 
834
      /* Generate.  */
 
835
      ec = generate_std (&sk, nbits, evalue, transient_key);
 
836
    }
 
837
 
 
838
  if (!ec)
 
839
    {
 
840
      skey[0] = sk.n;
 
841
      skey[1] = sk.e;
 
842
      skey[2] = sk.d;
 
843
      skey[3] = sk.p;
 
844
      skey[4] = sk.q;
 
845
      skey[5] = sk.u;
 
846
    }
 
847
  
 
848
  return ec;
 
849
}
 
850
 
 
851
 
 
852
static gcry_err_code_t
 
853
rsa_generate (int algo, unsigned int nbits, unsigned long evalue,
 
854
              gcry_mpi_t *skey, gcry_mpi_t **retfactors)
 
855
{
 
856
  return rsa_generate_ext (algo, nbits, evalue, NULL, skey, retfactors, NULL);
 
857
}
 
858
 
 
859
 
 
860
static gcry_err_code_t
 
861
rsa_check_secret_key (int algo, gcry_mpi_t *skey)
 
862
{
 
863
  gcry_err_code_t err = GPG_ERR_NO_ERROR;
 
864
  RSA_secret_key sk;
 
865
 
 
866
  (void)algo;
 
867
 
 
868
  sk.n = skey[0];
 
869
  sk.e = skey[1];
 
870
  sk.d = skey[2];
 
871
  sk.p = skey[3];
 
872
  sk.q = skey[4];
 
873
  sk.u = skey[5];
 
874
 
 
875
  if (!sk.p || !sk.q || !sk.u)
 
876
    err = GPG_ERR_NO_OBJ;  /* To check the key we need the optional
 
877
                              parameters. */
 
878
  else if (!check_secret_key (&sk))
 
879
    err = GPG_ERR_PUBKEY_ALGO;
 
880
 
 
881
  return err;
 
882
}
 
883
 
 
884
 
 
885
static gcry_err_code_t
 
886
rsa_encrypt (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
 
887
             gcry_mpi_t *pkey, int flags)
 
888
{
 
889
  RSA_public_key pk;
 
890
 
 
891
  (void)algo;
 
892
  (void)flags;
 
893
  
 
894
  pk.n = pkey[0];
 
895
  pk.e = pkey[1];
 
896
  resarr[0] = mpi_alloc (mpi_get_nlimbs (pk.n));
 
897
  public (resarr[0], data, &pk);
 
898
  
 
899
  return GPG_ERR_NO_ERROR;
 
900
}
 
901
 
 
902
 
 
903
static gcry_err_code_t
 
904
rsa_decrypt (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
 
905
             gcry_mpi_t *skey, int flags)
 
906
{
 
907
  RSA_secret_key sk;
 
908
  gcry_mpi_t r = MPI_NULL;      /* Random number needed for blinding.  */
 
909
  gcry_mpi_t ri = MPI_NULL;     /* Modular multiplicative inverse of
 
910
                                   r.  */
 
911
  gcry_mpi_t x = MPI_NULL;      /* Data to decrypt.  */
 
912
  gcry_mpi_t y;                 /* Result.  */
 
913
 
 
914
  (void)algo;
 
915
 
 
916
  /* Extract private key.  */
 
917
  sk.n = skey[0];
 
918
  sk.e = skey[1];
 
919
  sk.d = skey[2];
 
920
  sk.p = skey[3]; /* Optional. */
 
921
  sk.q = skey[4]; /* Optional. */
 
922
  sk.u = skey[5]; /* Optional. */
 
923
 
 
924
  y = gcry_mpi_snew (gcry_mpi_get_nbits (sk.n));
 
925
 
 
926
  /* We use blinding by default to mitigate timing attacks which can
 
927
     be practically mounted over the network as shown by Brumley and
 
928
     Boney in 2003.  */ 
 
929
  if (! (flags & PUBKEY_FLAG_NO_BLINDING))
 
930
    {
 
931
      /* Initialize blinding.  */
 
932
      
 
933
      /* First, we need a random number r between 0 and n - 1, which
 
934
         is relatively prime to n (i.e. it is neither p nor q).  The
 
935
         random number needs to be only unpredictable, thus we employ
 
936
         the gcry_create_nonce function by using GCRY_WEAK_RANDOM with
 
937
         gcry_mpi_randomize.  */
 
938
      r = gcry_mpi_snew (gcry_mpi_get_nbits (sk.n));
 
939
      ri = gcry_mpi_snew (gcry_mpi_get_nbits (sk.n));
 
940
      
 
941
      gcry_mpi_randomize (r, gcry_mpi_get_nbits (sk.n), GCRY_WEAK_RANDOM);
 
942
      gcry_mpi_mod (r, r, sk.n);
 
943
 
 
944
      /* Calculate inverse of r.  It practically impossible that the
 
945
         follwing test fails, thus we do not add code to release
 
946
         allocated resources.  */
 
947
      if (!gcry_mpi_invm (ri, r, sk.n))
 
948
        return GPG_ERR_INTERNAL;
 
949
    }
 
950
 
 
951
  if (! (flags & PUBKEY_FLAG_NO_BLINDING))
 
952
    x = rsa_blind (data[0], r, sk.e, sk.n);
 
953
  else
 
954
    x = data[0];
 
955
 
 
956
  /* Do the encryption.  */
 
957
  secret (y, x, &sk);
 
958
 
 
959
  if (! (flags & PUBKEY_FLAG_NO_BLINDING))
 
960
    {
 
961
      /* Undo blinding.  */
 
962
      gcry_mpi_t a = gcry_mpi_copy (y);
 
963
      
 
964
      gcry_mpi_release (y);
 
965
      y = rsa_unblind (a, ri, sk.n);
 
966
 
 
967
      gcry_mpi_release (a);
 
968
    }
 
969
 
 
970
  if (! (flags & PUBKEY_FLAG_NO_BLINDING))
 
971
    {
 
972
      /* Deallocate resources needed for blinding.  */
 
973
      gcry_mpi_release (x);
 
974
      gcry_mpi_release (r);
 
975
      gcry_mpi_release (ri);
 
976
    }
 
977
 
 
978
  /* Copy out result.  */
 
979
  *result = y;
 
980
  
 
981
  return GPG_ERR_NO_ERROR;
 
982
}
 
983
 
 
984
 
 
985
static gcry_err_code_t
 
986
rsa_sign (int algo, gcry_mpi_t *resarr, gcry_mpi_t data, gcry_mpi_t *skey)
 
987
{
 
988
  RSA_secret_key sk;
 
989
 
 
990
  (void)algo;
 
991
  
 
992
  sk.n = skey[0];
 
993
  sk.e = skey[1];
 
994
  sk.d = skey[2];
 
995
  sk.p = skey[3];
 
996
  sk.q = skey[4];
 
997
  sk.u = skey[5];
 
998
  resarr[0] = mpi_alloc( mpi_get_nlimbs (sk.n));
 
999
  secret (resarr[0], data, &sk);
 
1000
 
 
1001
  return GPG_ERR_NO_ERROR;
 
1002
}
 
1003
 
 
1004
 
 
1005
static gcry_err_code_t
 
1006
rsa_verify (int algo, gcry_mpi_t hash, gcry_mpi_t *data, gcry_mpi_t *pkey,
 
1007
                  int (*cmp) (void *opaque, gcry_mpi_t tmp),
 
1008
                  void *opaquev)
 
1009
{
 
1010
  RSA_public_key pk;
 
1011
  gcry_mpi_t result;
 
1012
  gcry_err_code_t rc;
 
1013
 
 
1014
  (void)algo;
 
1015
  (void)cmp;
 
1016
  (void)opaquev;
 
1017
 
 
1018
  pk.n = pkey[0];
 
1019
  pk.e = pkey[1];
 
1020
  result = gcry_mpi_new ( 160 );
 
1021
  public( result, data[0], &pk );
 
1022
#ifdef IS_DEVELOPMENT_VERSION
 
1023
  if (DBG_CIPHER)
 
1024
    {
 
1025
      log_mpidump ("rsa verify result:", result );
 
1026
      log_mpidump ("             hash:", hash );
 
1027
    }
 
1028
#endif /*IS_DEVELOPMENT_VERSION*/
 
1029
  /*rc = (*cmp)( opaquev, result );*/
 
1030
  rc = mpi_cmp (result, hash) ? GPG_ERR_BAD_SIGNATURE : GPG_ERR_NO_ERROR;
 
1031
  gcry_mpi_release (result);
 
1032
  
 
1033
  return rc;
 
1034
}
 
1035
 
 
1036
 
 
1037
static unsigned int
 
1038
rsa_get_nbits (int algo, gcry_mpi_t *pkey)
 
1039
{
 
1040
  (void)algo;
 
1041
 
 
1042
  return mpi_get_nbits (pkey[0]);
 
1043
}
 
1044
 
 
1045
 
 
1046
/* Compute a keygrip.  MD is the hash context which we are going to
 
1047
   update.  KEYPARAM is an S-expression with the key parameters, this
 
1048
   is usually a public key but may also be a secret key.  An example
 
1049
   of such an S-expression is:
 
1050
 
 
1051
      (rsa
 
1052
        (n #00B...#)
 
1053
        (e #010001#))
 
1054
        
 
1055
   PKCS-15 says that for RSA only the modulus should be hashed -
 
1056
   however, it is not clear wether this is meant to use the raw bytes
 
1057
   (assuming this is an unsigned integer) or whether the DER required
 
1058
   0 should be prefixed.  We hash the raw bytes.  */
 
1059
static gpg_err_code_t
 
1060
compute_keygrip (gcry_md_hd_t md, gcry_sexp_t keyparam)
 
1061
{
 
1062
  gcry_sexp_t l1;
 
1063
  const char *data;
 
1064
  size_t datalen;
 
1065
 
 
1066
  l1 = gcry_sexp_find_token (keyparam, "n", 1);
 
1067
  if (!l1)
 
1068
    return GPG_ERR_NO_OBJ;
 
1069
 
 
1070
  data = gcry_sexp_nth_data (l1, 1, &datalen);
 
1071
  if (!data)
 
1072
    {
 
1073
      gcry_sexp_release (l1);
 
1074
      return GPG_ERR_NO_OBJ;
 
1075
    }
 
1076
 
 
1077
  gcry_md_write (md, data, datalen);
 
1078
  gcry_sexp_release (l1);
 
1079
 
 
1080
  return 0;
 
1081
}
 
1082
 
 
1083
 
 
1084
 
 
1085
 
 
1086
/* 
 
1087
     Self-test section.
 
1088
 */
 
1089
 
 
1090
static const char *
 
1091
selftest_sign_1024 (gcry_sexp_t pkey, gcry_sexp_t skey)
 
1092
{
 
1093
  static const char sample_data[] = 
 
1094
    "(data (flags pkcs1)"
 
1095
    " (hash sha1 #11223344556677889900aabbccddeeff10203040#))";
 
1096
  static const char sample_data_bad[] = 
 
1097
    "(data (flags pkcs1)"
 
1098
    " (hash sha1 #11223344556677889900aabbccddeeff80203040#))";
 
1099
 
 
1100
  const char *errtxt = NULL;
 
1101
  gcry_error_t err;
 
1102
  gcry_sexp_t data = NULL;
 
1103
  gcry_sexp_t data_bad = NULL;
 
1104
  gcry_sexp_t sig = NULL;
 
1105
 
 
1106
  err = gcry_sexp_sscan (&data, NULL,
 
1107
                         sample_data, strlen (sample_data));
 
1108
  if (!err)
 
1109
    err = gcry_sexp_sscan (&data_bad, NULL, 
 
1110
                           sample_data_bad, strlen (sample_data_bad));
 
1111
  if (err)
 
1112
    {
 
1113
      errtxt = "converting data failed";
 
1114
      goto leave;
 
1115
    }
 
1116
 
 
1117
  err = gcry_pk_sign (&sig, data, skey);
 
1118
  if (err)
 
1119
    {
 
1120
      errtxt = "signing failed";
 
1121
      goto leave;
 
1122
    }
 
1123
  err = gcry_pk_verify (sig, data, pkey);
 
1124
  if (err)
 
1125
    {
 
1126
      errtxt = "verify failed";
 
1127
      goto leave;
 
1128
    }
 
1129
  err = gcry_pk_verify (sig, data_bad, pkey);
 
1130
  if (gcry_err_code (err) != GPG_ERR_BAD_SIGNATURE)
 
1131
    {
 
1132
      errtxt = "bad signature not detected";
 
1133
      goto leave;
 
1134
    }
 
1135
 
 
1136
 
 
1137
 leave:
 
1138
  gcry_sexp_release (sig);
 
1139
  gcry_sexp_release (data_bad);
 
1140
  gcry_sexp_release (data);
 
1141
  return errtxt;
 
1142
}
 
1143
 
 
1144
 
 
1145
 
 
1146
/* Given an S-expression ENCR_DATA of the form:
 
1147
 
 
1148
   (enc-val
 
1149
    (rsa
 
1150
     (a a-value)))
 
1151
 
 
1152
   as returned by gcry_pk_decrypt, return the the A-VALUE.  On error,
 
1153
   return NULL.  */
 
1154
static gcry_mpi_t
 
1155
extract_a_from_sexp (gcry_sexp_t encr_data)
 
1156
{
 
1157
  gcry_sexp_t l1, l2, l3;
 
1158
  gcry_mpi_t a_value;
 
1159
 
 
1160
  l1 = gcry_sexp_find_token (encr_data, "enc-val", 0);
 
1161
  if (!l1)
 
1162
    return NULL;
 
1163
  l2 = gcry_sexp_find_token (l1, "rsa", 0);
 
1164
  gcry_sexp_release (l1);
 
1165
  if (!l2)
 
1166
    return NULL;
 
1167
  l3 = gcry_sexp_find_token (l2, "a", 0);
 
1168
  gcry_sexp_release (l2);
 
1169
  if (!l3)
 
1170
    return NULL;
 
1171
  a_value = gcry_sexp_nth_mpi (l3, 1, 0);
 
1172
  gcry_sexp_release (l3);
 
1173
 
 
1174
  return a_value;
 
1175
}
 
1176
 
 
1177
 
 
1178
static const char *
 
1179
selftest_encr_1024 (gcry_sexp_t pkey, gcry_sexp_t skey)
 
1180
{
 
1181
  const char *errtxt = NULL;
 
1182
  gcry_error_t err;
 
1183
  const unsigned int nbits = 1000; /* Encrypt 1000 random bits.  */
 
1184
  gcry_mpi_t plaintext = NULL;
 
1185
  gcry_sexp_t plain = NULL;
 
1186
  gcry_sexp_t encr  = NULL;
 
1187
  gcry_mpi_t  ciphertext = NULL;
 
1188
  gcry_sexp_t decr  = NULL;
 
1189
  gcry_mpi_t  decr_plaintext = NULL;
 
1190
  gcry_sexp_t tmplist = NULL;
 
1191
 
 
1192
  /* Create plaintext.  The plaintext is actually a big integer number.  */
 
1193
  plaintext = gcry_mpi_new (nbits);
 
1194
  gcry_mpi_randomize (plaintext, nbits, GCRY_WEAK_RANDOM);
 
1195
  
 
1196
  /* Put the plaintext into an S-expression.  */
 
1197
  err = gcry_sexp_build (&plain, NULL,
 
1198
                         "(data (flags raw) (value %m))", plaintext);
 
1199
  if (err)
 
1200
    {
 
1201
      errtxt = "converting data failed";
 
1202
      goto leave;
 
1203
    }
 
1204
 
 
1205
  /* Encrypt.  */
 
1206
  err = gcry_pk_encrypt (&encr, plain, pkey);
 
1207
  if (err)
 
1208
    {
 
1209
      errtxt = "encrypt failed";
 
1210
      goto leave;
 
1211
    }
 
1212
 
 
1213
  /* Extraxt the ciphertext from the returned S-expression.  */
 
1214
  /*gcry_sexp_dump (encr);*/
 
1215
  ciphertext = extract_a_from_sexp (encr);
 
1216
  if (!ciphertext)
 
1217
    {
 
1218
      errtxt = "gcry_pk_decrypt returned garbage";
 
1219
      goto leave;
 
1220
    }
 
1221
 
 
1222
  /* Check that the ciphertext does no match the plaintext.  */
 
1223
  /* _gcry_log_mpidump ("plaintext", plaintext); */
 
1224
  /* _gcry_log_mpidump ("ciphertxt", ciphertext); */
 
1225
  if (!gcry_mpi_cmp (plaintext, ciphertext))
 
1226
    {
 
1227
      errtxt = "ciphertext matches plaintext";
 
1228
      goto leave;
 
1229
    }
 
1230
 
 
1231
  /* Decrypt.  */
 
1232
  err = gcry_pk_decrypt (&decr, encr, skey);
 
1233
  if (err)
 
1234
    {
 
1235
      errtxt = "decrypt failed";
 
1236
      goto leave;
 
1237
    }
 
1238
 
 
1239
  /* Extract the decrypted data from the S-expression.  Note that the
 
1240
     output of gcry_pk_decrypt depends on whether a flags lists occurs
 
1241
     in its input data.  Because we passed the output of
 
1242
     gcry_pk_encrypt directly to gcry_pk_decrypt, such a flag value
 
1243
     won't be there as of today.  To be prepared for future changes we
 
1244
     take care of it anyway.  */
 
1245
  tmplist = gcry_sexp_find_token (decr, "value", 0);
 
1246
  if (tmplist)
 
1247
    decr_plaintext = gcry_sexp_nth_mpi (tmplist, 1, GCRYMPI_FMT_USG);
 
1248
  else
 
1249
    decr_plaintext = gcry_sexp_nth_mpi (decr, 0, GCRYMPI_FMT_USG);
 
1250
  if (!decr_plaintext)
 
1251
    {
 
1252
      errtxt = "decrypt returned no plaintext";
 
1253
      goto leave;
 
1254
    }
 
1255
  
 
1256
  /* Check that the decrypted plaintext matches the original  plaintext.  */
 
1257
  if (gcry_mpi_cmp (plaintext, decr_plaintext))
 
1258
    {
 
1259
      errtxt = "mismatch";
 
1260
      goto leave;
 
1261
    }
 
1262
 
 
1263
 leave:
 
1264
  gcry_sexp_release (tmplist);
 
1265
  gcry_mpi_release (decr_plaintext);
 
1266
  gcry_sexp_release (decr);
 
1267
  gcry_mpi_release (ciphertext);
 
1268
  gcry_sexp_release (encr);
 
1269
  gcry_sexp_release (plain);
 
1270
  gcry_mpi_release (plaintext);
 
1271
  return errtxt;
 
1272
}
 
1273
 
 
1274
 
 
1275
static gpg_err_code_t
 
1276
selftests_rsa (selftest_report_func_t report)
 
1277
{
 
1278
  const char *what;
 
1279
  const char *errtxt;
 
1280
  gcry_error_t err;
 
1281
  gcry_sexp_t skey = NULL;
 
1282
  gcry_sexp_t pkey = NULL;
 
1283
  
 
1284
  /* Convert the S-expressions into the internal representation.  */
 
1285
  what = "convert";
 
1286
  err = gcry_sexp_sscan (&skey, NULL, 
 
1287
                         sample_secret_key, strlen (sample_secret_key));
 
1288
  if (!err)
 
1289
    err = gcry_sexp_sscan (&pkey, NULL, 
 
1290
                           sample_public_key, strlen (sample_public_key));
 
1291
  if (err)
 
1292
    {
 
1293
      errtxt = gcry_strerror (err);
 
1294
      goto failed;
 
1295
    }
 
1296
 
 
1297
  what = "key consistency";
 
1298
  err = gcry_pk_testkey (skey);
 
1299
  if (err)
 
1300
    {
 
1301
      errtxt = gcry_strerror (err);
 
1302
      goto failed;
 
1303
    }
 
1304
 
 
1305
  what = "sign";
 
1306
  errtxt = selftest_sign_1024 (pkey, skey);
 
1307
  if (errtxt)
 
1308
    goto failed;
 
1309
 
 
1310
  what = "encrypt";
 
1311
  errtxt = selftest_encr_1024 (pkey, skey);
 
1312
  if (errtxt)
 
1313
    goto failed;
 
1314
 
 
1315
  gcry_sexp_release (pkey);
 
1316
  gcry_sexp_release (skey);
 
1317
  return 0; /* Succeeded. */
 
1318
 
 
1319
 failed:
 
1320
  gcry_sexp_release (pkey);
 
1321
  gcry_sexp_release (skey);
 
1322
  if (report)
 
1323
    report ("pubkey", GCRY_PK_RSA, what, errtxt);
 
1324
  return GPG_ERR_SELFTEST_FAILED;
 
1325
}
 
1326
 
 
1327
 
 
1328
/* Run a full self-test for ALGO and return 0 on success.  */
 
1329
static gpg_err_code_t
 
1330
run_selftests (int algo, int extended, selftest_report_func_t report)
 
1331
{
 
1332
  gpg_err_code_t ec;
 
1333
 
 
1334
  (void)extended;
 
1335
 
 
1336
  switch (algo)
 
1337
    {
 
1338
    case GCRY_PK_RSA:
 
1339
      ec = selftests_rsa (report);
 
1340
      break;
 
1341
    default:
 
1342
      ec = GPG_ERR_PUBKEY_ALGO;
 
1343
      break;
 
1344
        
 
1345
    }
 
1346
  return ec;
 
1347
}
 
1348
 
 
1349
 
 
1350
 
 
1351
 
 
1352
static const char *rsa_names[] =
 
1353
  {
 
1354
    "rsa",
 
1355
    "openpgp-rsa",
 
1356
    "oid.1.2.840.113549.1.1.1",
 
1357
    NULL,
 
1358
  };
 
1359
 
 
1360
gcry_pk_spec_t _gcry_pubkey_spec_rsa =
 
1361
  {
 
1362
    "RSA", rsa_names,
 
1363
    "ne", "nedpqu", "a", "s", "n",
 
1364
    GCRY_PK_USAGE_SIGN | GCRY_PK_USAGE_ENCR,
 
1365
    rsa_generate,
 
1366
    rsa_check_secret_key,
 
1367
    rsa_encrypt,
 
1368
    rsa_decrypt,
 
1369
    rsa_sign,
 
1370
    rsa_verify,
 
1371
    rsa_get_nbits,
 
1372
  };
 
1373
pk_extra_spec_t _gcry_pubkey_extraspec_rsa = 
 
1374
  {
 
1375
    run_selftests,
 
1376
    rsa_generate_ext,
 
1377
    compute_keygrip
 
1378
  };
 
1379