1/* pubkey.c  -	pubkey dispatcher
2 * Copyright (C) 1998, 1999, 2000, 2002, 2003, 2005,
3 *               2007, 2008, 2011 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#include <config.h>
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25#include <errno.h>
26
27#include "g10lib.h"
28#include "mpi.h"
29#include "cipher.h"
30#include "ath.h"
31
32
33static gcry_err_code_t pubkey_decrypt (int algo, gcry_mpi_t *result,
34                                       gcry_mpi_t *data, gcry_mpi_t *skey,
35                                       int flags);
36static gcry_err_code_t pubkey_sign (int algo, gcry_mpi_t *resarr,
37                                    gcry_mpi_t hash, gcry_mpi_t *skey);
38static gcry_err_code_t pubkey_verify (int algo, gcry_mpi_t hash,
39                                      gcry_mpi_t *data, gcry_mpi_t *pkey,
40				     int (*cmp) (void *, gcry_mpi_t),
41                                      void *opaque);
42
43
44/* A dummy extraspec so that we do not need to tests the extraspec
45   field from the module specification against NULL and instead
46   directly test the respective fields of extraspecs.  */
47static pk_extra_spec_t dummy_extra_spec;
48
49
50/* This is the list of the default public-key ciphers included in
51   libgcrypt.  FIPS_ALLOWED indicated whether the algorithm is used in
52   FIPS mode. */
53static struct pubkey_table_entry
54{
55  gcry_pk_spec_t *pubkey;
56  pk_extra_spec_t *extraspec;
57  unsigned int algorithm;
58  int fips_allowed;
59} pubkey_table[] =
60  {
61#if USE_RSA
62    { &_gcry_pubkey_spec_rsa,
63      &_gcry_pubkey_extraspec_rsa,   GCRY_PK_RSA, 1},
64#endif
65#if USE_ELGAMAL
66    { &_gcry_pubkey_spec_elg,
67      &_gcry_pubkey_extraspec_elg,    GCRY_PK_ELG   },
68    { &_gcry_pubkey_spec_elg,
69      &_gcry_pubkey_extraspec_elg,    GCRY_PK_ELG_E },
70#endif
71#if USE_DSA
72    { &_gcry_pubkey_spec_dsa,
73      &_gcry_pubkey_extraspec_dsa,   GCRY_PK_DSA, 1   },
74#endif
75#if USE_ECC
76    { &_gcry_pubkey_spec_ecdsa,
77      &_gcry_pubkey_extraspec_ecdsa, GCRY_PK_ECDSA, 0 },
78    { &_gcry_pubkey_spec_ecdh,
79      &_gcry_pubkey_extraspec_ecdsa, GCRY_PK_ECDH, 0 },
80#endif
81    { NULL, 0 },
82  };
83
84/* List of registered ciphers.  */
85static gcry_module_t pubkeys_registered;
86
87/* This is the lock protecting PUBKEYS_REGISTERED.  */
88static ath_mutex_t pubkeys_registered_lock = ATH_MUTEX_INITIALIZER;;
89
90/* Flag to check whether the default pubkeys have already been
91   registered.  */
92static int default_pubkeys_registered;
93
94/* Convenient macro for registering the default digests.  */
95#define REGISTER_DEFAULT_PUBKEYS                   \
96  do                                               \
97    {                                              \
98      ath_mutex_lock (&pubkeys_registered_lock);   \
99      if (! default_pubkeys_registered)            \
100        {                                          \
101          pk_register_default ();                  \
102          default_pubkeys_registered = 1;          \
103        }                                          \
104      ath_mutex_unlock (&pubkeys_registered_lock); \
105    }                                              \
106  while (0)
107
108/* These dummy functions are used in case a cipher implementation
109   refuses to provide it's own functions.  */
110
111static gcry_err_code_t
112dummy_generate (int algorithm, unsigned int nbits, unsigned long dummy,
113                gcry_mpi_t *skey, gcry_mpi_t **retfactors)
114{
115  (void)algorithm;
116  (void)nbits;
117  (void)dummy;
118  (void)skey;
119  (void)retfactors;
120  fips_signal_error ("using dummy public key function");
121  return GPG_ERR_NOT_IMPLEMENTED;
122}
123
124static gcry_err_code_t
125dummy_check_secret_key (int algorithm, gcry_mpi_t *skey)
126{
127  (void)algorithm;
128  (void)skey;
129  fips_signal_error ("using dummy public key function");
130  return GPG_ERR_NOT_IMPLEMENTED;
131}
132
133static gcry_err_code_t
134dummy_encrypt (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
135               gcry_mpi_t *pkey, int flags)
136{
137  (void)algorithm;
138  (void)resarr;
139  (void)data;
140  (void)pkey;
141  (void)flags;
142  fips_signal_error ("using dummy public key function");
143  return GPG_ERR_NOT_IMPLEMENTED;
144}
145
146static gcry_err_code_t
147dummy_decrypt (int algorithm, gcry_mpi_t *result, gcry_mpi_t *data,
148               gcry_mpi_t *skey, int flags)
149{
150  (void)algorithm;
151  (void)result;
152  (void)data;
153  (void)skey;
154  (void)flags;
155  fips_signal_error ("using dummy public key function");
156  return GPG_ERR_NOT_IMPLEMENTED;
157}
158
159static gcry_err_code_t
160dummy_sign (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
161            gcry_mpi_t *skey)
162{
163  (void)algorithm;
164  (void)resarr;
165  (void)data;
166  (void)skey;
167  fips_signal_error ("using dummy public key function");
168  return GPG_ERR_NOT_IMPLEMENTED;
169}
170
171static gcry_err_code_t
172dummy_verify (int algorithm, gcry_mpi_t hash, gcry_mpi_t *data,
173              gcry_mpi_t *pkey,
174	      int (*cmp) (void *, gcry_mpi_t), void *opaquev)
175{
176  (void)algorithm;
177  (void)hash;
178  (void)data;
179  (void)pkey;
180  (void)cmp;
181  (void)opaquev;
182  fips_signal_error ("using dummy public key function");
183  return GPG_ERR_NOT_IMPLEMENTED;
184}
185
186static unsigned
187dummy_get_nbits (int algorithm, gcry_mpi_t *pkey)
188{
189  (void)algorithm;
190  (void)pkey;
191  fips_signal_error ("using dummy public key function");
192  return 0;
193}
194
195/* Internal function.  Register all the pubkeys included in
196   PUBKEY_TABLE.  Returns zero on success or an error code.  */
197static void
198pk_register_default (void)
199{
200  gcry_err_code_t err = 0;
201  int i;
202
203  for (i = 0; (! err) && pubkey_table[i].pubkey; i++)
204    {
205#define pubkey_use_dummy(func)                       \
206      if (! pubkey_table[i].pubkey->func)            \
207	pubkey_table[i].pubkey->func = dummy_##func;
208
209      pubkey_use_dummy (generate);
210      pubkey_use_dummy (check_secret_key);
211      pubkey_use_dummy (encrypt);
212      pubkey_use_dummy (decrypt);
213      pubkey_use_dummy (sign);
214      pubkey_use_dummy (verify);
215      pubkey_use_dummy (get_nbits);
216#undef pubkey_use_dummy
217
218      err = _gcry_module_add (&pubkeys_registered,
219			      pubkey_table[i].algorithm,
220			      (void *) pubkey_table[i].pubkey,
221			      (void *) pubkey_table[i].extraspec,
222                              NULL);
223    }
224
225  if (err)
226    BUG ();
227}
228
229/* Internal callback function.  Used via _gcry_module_lookup.  */
230static int
231gcry_pk_lookup_func_name (void *spec, void *data)
232{
233  gcry_pk_spec_t *pubkey = (gcry_pk_spec_t *) spec;
234  char *name = (char *) data;
235  const char **aliases = pubkey->aliases;
236  int ret = stricmp (name, pubkey->name);
237
238  while (ret && *aliases)
239    ret = stricmp (name, *aliases++);
240
241  return ! ret;
242}
243
244/* Internal function.  Lookup a pubkey entry by it's name.  */
245static gcry_module_t
246gcry_pk_lookup_name (const char *name)
247{
248  gcry_module_t pubkey;
249
250  pubkey = _gcry_module_lookup (pubkeys_registered, (void *) name,
251				gcry_pk_lookup_func_name);
252
253  return pubkey;
254}
255
256/* Register a new pubkey module whose specification can be found in
257   PUBKEY.  On success, a new algorithm ID is stored in ALGORITHM_ID
258   and a pointer representhing this module is stored in MODULE.  */
259gcry_error_t
260_gcry_pk_register (gcry_pk_spec_t *pubkey,
261                   pk_extra_spec_t *extraspec,
262                   unsigned int *algorithm_id,
263                   gcry_module_t *module)
264{
265  gcry_err_code_t err = GPG_ERR_NO_ERROR;
266  gcry_module_t mod;
267
268  /* We do not support module loading in fips mode.  */
269  if (fips_mode ())
270    return gpg_error (GPG_ERR_NOT_SUPPORTED);
271
272  ath_mutex_lock (&pubkeys_registered_lock);
273  err = _gcry_module_add (&pubkeys_registered, 0,
274			  (void *) pubkey,
275			  (void *)(extraspec? extraspec : &dummy_extra_spec),
276                          &mod);
277  ath_mutex_unlock (&pubkeys_registered_lock);
278
279  if (! err)
280    {
281      *module = mod;
282      *algorithm_id = mod->mod_id;
283    }
284
285  return err;
286}
287
288/* Unregister the pubkey identified by ID, which must have been
289   registered with gcry_pk_register.  */
290void
291gcry_pk_unregister (gcry_module_t module)
292{
293  ath_mutex_lock (&pubkeys_registered_lock);
294  _gcry_module_release (module);
295  ath_mutex_unlock (&pubkeys_registered_lock);
296}
297
298static void
299release_mpi_array (gcry_mpi_t *array)
300{
301  for (; *array; array++)
302    {
303      mpi_free(*array);
304      *array = NULL;
305    }
306}
307
308/****************
309 * Map a string to the pubkey algo
310 */
311int
312gcry_pk_map_name (const char *string)
313{
314  gcry_module_t pubkey;
315  int algorithm = 0;
316
317  if (!string)
318    return 0;
319
320  REGISTER_DEFAULT_PUBKEYS;
321
322  ath_mutex_lock (&pubkeys_registered_lock);
323  pubkey = gcry_pk_lookup_name (string);
324  if (pubkey)
325    {
326      algorithm = pubkey->mod_id;
327      _gcry_module_release (pubkey);
328    }
329  ath_mutex_unlock (&pubkeys_registered_lock);
330
331  return algorithm;
332}
333
334
335/* Map the public key algorithm whose ID is contained in ALGORITHM to
336   a string representation of the algorithm name.  For unknown
337   algorithm IDs this functions returns "?". */
338const char *
339gcry_pk_algo_name (int algorithm)
340{
341  gcry_module_t pubkey;
342  const char *name;
343
344  REGISTER_DEFAULT_PUBKEYS;
345
346  ath_mutex_lock (&pubkeys_registered_lock);
347  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
348  if (pubkey)
349    {
350      name = ((gcry_pk_spec_t *) pubkey->spec)->name;
351      _gcry_module_release (pubkey);
352    }
353  else
354    name = "?";
355  ath_mutex_unlock (&pubkeys_registered_lock);
356
357  return name;
358}
359
360
361/* A special version of gcry_pk_algo name to return the first aliased
362   name of the algorithm.  This is required to adhere to the spki
363   specs where the algorithm names are lowercase. */
364const char *
365_gcry_pk_aliased_algo_name (int algorithm)
366{
367  const char *name = NULL;
368  gcry_module_t module;
369
370  REGISTER_DEFAULT_PUBKEYS;
371
372  ath_mutex_lock (&pubkeys_registered_lock);
373  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
374  if (module)
375    {
376      gcry_pk_spec_t *pubkey = (gcry_pk_spec_t *) module->spec;
377
378      name = pubkey->aliases? *pubkey->aliases : NULL;
379      if (!name || !*name)
380        name = pubkey->name;
381      _gcry_module_release (module);
382    }
383  ath_mutex_unlock (&pubkeys_registered_lock);
384
385  return name;
386}
387
388
389static void
390disable_pubkey_algo (int algorithm)
391{
392  gcry_module_t pubkey;
393
394  ath_mutex_lock (&pubkeys_registered_lock);
395  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
396  if (pubkey)
397    {
398      if (! (pubkey-> flags & FLAG_MODULE_DISABLED))
399	pubkey->flags |= FLAG_MODULE_DISABLED;
400      _gcry_module_release (pubkey);
401    }
402  ath_mutex_unlock (&pubkeys_registered_lock);
403}
404
405
406/****************
407 * A USE of 0 means: don't care.
408 */
409static gcry_err_code_t
410check_pubkey_algo (int algorithm, unsigned use)
411{
412  gcry_err_code_t err = GPG_ERR_NO_ERROR;
413  gcry_pk_spec_t *pubkey;
414  gcry_module_t module;
415
416  REGISTER_DEFAULT_PUBKEYS;
417
418  ath_mutex_lock (&pubkeys_registered_lock);
419  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
420  if (module)
421    {
422      pubkey = (gcry_pk_spec_t *) module->spec;
423
424      if (((use & GCRY_PK_USAGE_SIGN)
425	   && (! (pubkey->use & GCRY_PK_USAGE_SIGN)))
426	  || ((use & GCRY_PK_USAGE_ENCR)
427	      && (! (pubkey->use & GCRY_PK_USAGE_ENCR))))
428	err = GPG_ERR_WRONG_PUBKEY_ALGO;
429      else if (module->flags & FLAG_MODULE_DISABLED)
430	err = GPG_ERR_PUBKEY_ALGO;
431      _gcry_module_release (module);
432    }
433  else
434    err = GPG_ERR_PUBKEY_ALGO;
435  ath_mutex_unlock (&pubkeys_registered_lock);
436
437  return err;
438}
439
440
441/****************
442 * Return the number of public key material numbers
443 */
444static int
445pubkey_get_npkey (int algorithm)
446{
447  gcry_module_t pubkey;
448  int npkey = 0;
449
450  REGISTER_DEFAULT_PUBKEYS;
451
452  ath_mutex_lock (&pubkeys_registered_lock);
453  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
454  if (pubkey)
455    {
456      npkey = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_pkey);
457      _gcry_module_release (pubkey);
458    }
459  ath_mutex_unlock (&pubkeys_registered_lock);
460
461  return npkey;
462}
463
464/****************
465 * Return the number of secret key material numbers
466 */
467static int
468pubkey_get_nskey (int algorithm)
469{
470  gcry_module_t pubkey;
471  int nskey = 0;
472
473  REGISTER_DEFAULT_PUBKEYS;
474
475  ath_mutex_lock (&pubkeys_registered_lock);
476  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
477  if (pubkey)
478    {
479      nskey = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_skey);
480      _gcry_module_release (pubkey);
481    }
482  ath_mutex_unlock (&pubkeys_registered_lock);
483
484  return nskey;
485}
486
487/****************
488 * Return the number of signature material numbers
489 */
490static int
491pubkey_get_nsig (int algorithm)
492{
493  gcry_module_t pubkey;
494  int nsig = 0;
495
496  REGISTER_DEFAULT_PUBKEYS;
497
498  ath_mutex_lock (&pubkeys_registered_lock);
499  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
500  if (pubkey)
501    {
502      nsig = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_sig);
503      _gcry_module_release (pubkey);
504    }
505  ath_mutex_unlock (&pubkeys_registered_lock);
506
507  return nsig;
508}
509
510/****************
511 * Return the number of encryption material numbers
512 */
513static int
514pubkey_get_nenc (int algorithm)
515{
516  gcry_module_t pubkey;
517  int nenc = 0;
518
519  REGISTER_DEFAULT_PUBKEYS;
520
521  ath_mutex_lock (&pubkeys_registered_lock);
522  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
523  if (pubkey)
524    {
525      nenc = strlen (((gcry_pk_spec_t *) pubkey->spec)->elements_enc);
526      _gcry_module_release (pubkey);
527    }
528  ath_mutex_unlock (&pubkeys_registered_lock);
529
530  return nenc;
531}
532
533
534/* Generate a new public key with algorithm ALGORITHM of size NBITS
535   and return it at SKEY.  USE_E depends on the ALGORITHM.  GENPARMS
536   is passed to the algorithm module if it features an extended
537   generation function.  RETFACTOR is used by some algorithms to
538   return certain additional information which are in general not
539   required.
540
541   The function returns the error code number or 0 on success. */
542static gcry_err_code_t
543pubkey_generate (int algorithm,
544                 unsigned int nbits,
545                 unsigned long use_e,
546                 gcry_sexp_t genparms,
547                 gcry_mpi_t *skey, gcry_mpi_t **retfactors,
548                 gcry_sexp_t *r_extrainfo)
549{
550  gcry_err_code_t ec = GPG_ERR_PUBKEY_ALGO;
551  gcry_module_t pubkey;
552
553  REGISTER_DEFAULT_PUBKEYS;
554
555  ath_mutex_lock (&pubkeys_registered_lock);
556  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
557  if (pubkey)
558    {
559      pk_extra_spec_t *extraspec = pubkey->extraspec;
560
561      if (extraspec && extraspec->ext_generate)
562        {
563          /* Use the extended generate function.  */
564          ec = extraspec->ext_generate
565            (algorithm, nbits, use_e, genparms, skey, retfactors, r_extrainfo);
566        }
567      else
568        {
569          /* Use the standard generate function.  */
570          ec = ((gcry_pk_spec_t *) pubkey->spec)->generate
571            (algorithm, nbits, use_e, skey, retfactors);
572        }
573      _gcry_module_release (pubkey);
574    }
575  ath_mutex_unlock (&pubkeys_registered_lock);
576
577  return ec;
578}
579
580
581static gcry_err_code_t
582pubkey_check_secret_key (int algorithm, gcry_mpi_t *skey)
583{
584  gcry_err_code_t err = GPG_ERR_PUBKEY_ALGO;
585  gcry_module_t pubkey;
586
587  REGISTER_DEFAULT_PUBKEYS;
588
589  ath_mutex_lock (&pubkeys_registered_lock);
590  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
591  if (pubkey)
592    {
593      err = ((gcry_pk_spec_t *) pubkey->spec)->check_secret_key
594        (algorithm, skey);
595      _gcry_module_release (pubkey);
596    }
597  ath_mutex_unlock (&pubkeys_registered_lock);
598
599  return err;
600}
601
602
603/****************
604 * This is the interface to the public key encryption.  Encrypt DATA
605 * with PKEY and put it into RESARR which should be an array of MPIs
606 * of size PUBKEY_MAX_NENC (or less if the algorithm allows this -
607 * check with pubkey_get_nenc() )
608 */
609static gcry_err_code_t
610pubkey_encrypt (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
611                gcry_mpi_t *pkey, int flags)
612{
613  gcry_pk_spec_t *pubkey;
614  gcry_module_t module;
615  gcry_err_code_t rc;
616  int i;
617
618  /* Note: In fips mode DBG_CIPHER will enver evaluate to true but as
619     an extra failsafe protection we explicitly test for fips mode
620     here. */
621  if (DBG_CIPHER && !fips_mode ())
622    {
623      log_debug ("pubkey_encrypt: algo=%d\n", algorithm);
624      for(i = 0; i < pubkey_get_npkey (algorithm); i++)
625	log_mpidump ("  pkey:", pkey[i]);
626      log_mpidump ("  data:", data);
627    }
628
629  ath_mutex_lock (&pubkeys_registered_lock);
630  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
631  if (module)
632    {
633      pubkey = (gcry_pk_spec_t *) module->spec;
634      rc = pubkey->encrypt (algorithm, resarr, data, pkey, flags);
635      _gcry_module_release (module);
636      goto ready;
637    }
638  rc = GPG_ERR_PUBKEY_ALGO;
639
640 ready:
641  ath_mutex_unlock (&pubkeys_registered_lock);
642
643  if (!rc && DBG_CIPHER && !fips_mode ())
644    {
645      for(i = 0; i < pubkey_get_nenc (algorithm); i++)
646	log_mpidump("  encr:", resarr[i] );
647    }
648  return rc;
649}
650
651
652/****************
653 * This is the interface to the public key decryption.
654 * ALGO gives the algorithm to use and this implicitly determines
655 * the size of the arrays.
656 * result is a pointer to a mpi variable which will receive a
657 * newly allocated mpi or NULL in case of an error.
658 */
659static gcry_err_code_t
660pubkey_decrypt (int algorithm, gcry_mpi_t *result, gcry_mpi_t *data,
661                gcry_mpi_t *skey, int flags)
662{
663  gcry_pk_spec_t *pubkey;
664  gcry_module_t module;
665  gcry_err_code_t rc;
666  int i;
667
668  *result = NULL; /* so the caller can always do a mpi_free */
669  if (DBG_CIPHER && !fips_mode ())
670    {
671      log_debug ("pubkey_decrypt: algo=%d\n", algorithm);
672      for(i = 0; i < pubkey_get_nskey (algorithm); i++)
673	log_mpidump ("  skey:", skey[i]);
674      for(i = 0; i < pubkey_get_nenc (algorithm); i++)
675	log_mpidump ("  data:", data[i]);
676    }
677
678  ath_mutex_lock (&pubkeys_registered_lock);
679  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
680  if (module)
681    {
682      pubkey = (gcry_pk_spec_t *) module->spec;
683      rc = pubkey->decrypt (algorithm, result, data, skey, flags);
684      _gcry_module_release (module);
685      goto ready;
686    }
687
688  rc = GPG_ERR_PUBKEY_ALGO;
689
690 ready:
691  ath_mutex_unlock (&pubkeys_registered_lock);
692
693  if (!rc && DBG_CIPHER && !fips_mode ())
694    log_mpidump (" plain:", *result);
695
696  return rc;
697}
698
699
700/****************
701 * This is the interface to the public key signing.
702 * Sign data with skey and put the result into resarr which
703 * should be an array of MPIs of size PUBKEY_MAX_NSIG (or less if the
704 * algorithm allows this - check with pubkey_get_nsig() )
705 */
706static gcry_err_code_t
707pubkey_sign (int algorithm, gcry_mpi_t *resarr, gcry_mpi_t data,
708             gcry_mpi_t *skey)
709{
710  gcry_pk_spec_t *pubkey;
711  gcry_module_t module;
712  gcry_err_code_t rc;
713  int i;
714
715  if (DBG_CIPHER && !fips_mode ())
716    {
717      log_debug ("pubkey_sign: algo=%d\n", algorithm);
718      for(i = 0; i < pubkey_get_nskey (algorithm); i++)
719	log_mpidump ("  skey:", skey[i]);
720      log_mpidump("  data:", data );
721    }
722
723  ath_mutex_lock (&pubkeys_registered_lock);
724  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
725  if (module)
726    {
727      pubkey = (gcry_pk_spec_t *) module->spec;
728      rc = pubkey->sign (algorithm, resarr, data, skey);
729      _gcry_module_release (module);
730      goto ready;
731    }
732
733  rc = GPG_ERR_PUBKEY_ALGO;
734
735 ready:
736  ath_mutex_unlock (&pubkeys_registered_lock);
737
738  if (!rc && DBG_CIPHER && !fips_mode ())
739    for (i = 0; i < pubkey_get_nsig (algorithm); i++)
740      log_mpidump ("   sig:", resarr[i]);
741
742  return rc;
743}
744
745/****************
746 * Verify a public key signature.
747 * Return 0 if the signature is good
748 */
749static gcry_err_code_t
750pubkey_verify (int algorithm, gcry_mpi_t hash, gcry_mpi_t *data,
751               gcry_mpi_t *pkey,
752	       int (*cmp)(void *, gcry_mpi_t), void *opaquev)
753{
754  gcry_pk_spec_t *pubkey;
755  gcry_module_t module;
756  gcry_err_code_t rc;
757  int i;
758
759  if (DBG_CIPHER && !fips_mode ())
760    {
761      log_debug ("pubkey_verify: algo=%d\n", algorithm);
762      for (i = 0; i < pubkey_get_npkey (algorithm); i++)
763	log_mpidump ("  pkey", pkey[i]);
764      for (i = 0; i < pubkey_get_nsig (algorithm); i++)
765	log_mpidump ("   sig", data[i]);
766      log_mpidump ("  hash", hash);
767    }
768
769  ath_mutex_lock (&pubkeys_registered_lock);
770  module = _gcry_module_lookup_id (pubkeys_registered, algorithm);
771  if (module)
772    {
773      pubkey = (gcry_pk_spec_t *) module->spec;
774      rc = pubkey->verify (algorithm, hash, data, pkey, cmp, opaquev);
775      _gcry_module_release (module);
776      goto ready;
777    }
778
779  rc = GPG_ERR_PUBKEY_ALGO;
780
781 ready:
782  ath_mutex_unlock (&pubkeys_registered_lock);
783  return rc;
784}
785
786
787/* Turn VALUE into an octet string and store it in an allocated buffer
788   at R_FRAME or - if R_RAME is NULL - copy it into the caller
789   provided buffer SPACE; either SPACE or R_FRAME may be used.  If
790   SPACE if not NULL, the caller must provide a buffer of at least
791   NBYTES.  If the resulting octet string is shorter than NBYTES pad
792   it to the left with zeroes.  If VALUE does not fit into NBYTES
793   return an error code.  */
794static gpg_err_code_t
795octet_string_from_mpi (unsigned char **r_frame, void *space,
796                       gcry_mpi_t value, size_t nbytes)
797{
798  gpg_err_code_t rc;
799  size_t nframe, noff, n;
800  unsigned char *frame;
801
802  if (!r_frame == !space)
803    return GPG_ERR_INV_ARG;  /* Only one may be used.  */
804
805  if (r_frame)
806    *r_frame = NULL;
807
808  rc = gcry_err_code (gcry_mpi_print (GCRYMPI_FMT_USG,
809                                      NULL, 0, &nframe, value));
810  if (rc)
811    return rc;
812  if (nframe > nbytes)
813    return GPG_ERR_TOO_LARGE; /* Value too long to fit into NBYTES.  */
814
815  noff = (nframe < nbytes)? nbytes - nframe : 0;
816  n = nframe + noff;
817  if (space)
818    frame = space;
819  else
820    {
821      frame = mpi_is_secure (value)? gcry_malloc_secure (n) : gcry_malloc (n);
822      if (!frame)
823        {
824          rc = gpg_err_code_from_syserror ();
825          return rc;
826        }
827    }
828  if (noff)
829    memset (frame, 0, noff);
830  nframe += noff;
831  rc = gcry_err_code (gcry_mpi_print (GCRYMPI_FMT_USG,
832                                      frame+noff, nframe-noff, NULL, value));
833  if (rc)
834    {
835      gcry_free (frame);
836      return rc;
837    }
838
839  if (r_frame)
840    *r_frame = frame;
841  return 0;
842}
843
844
845/* Encode {VALUE,VALUELEN} for an NBITS keys using the pkcs#1 block
846   type 2 padding.  On sucess the result is stored as a new MPI at
847   R_RESULT.  On error the value at R_RESULT is undefined.
848
849   If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as
850   the seed instead of using a random string for it.  This feature is
851   only useful for regression tests.  Note that this value may not
852   contain zero bytes.
853
854   We encode the value in this way:
855
856     0  2  RND(n bytes)  0  VALUE
857
858   0   is a marker we unfortunately can't encode because we return an
859       MPI which strips all leading zeroes.
860   2   is the block type.
861   RND are non-zero random bytes.
862
863   (Note that OpenPGP includes the cipher algorithm and a checksum in
864   VALUE; the caller needs to prepare the value accordingly.)
865  */
866static gcry_err_code_t
867pkcs1_encode_for_encryption (gcry_mpi_t *r_result, unsigned int nbits,
868			     const unsigned char *value, size_t valuelen,
869                             const unsigned char *random_override,
870                             size_t random_override_len)
871{
872  gcry_err_code_t rc = 0;
873  gcry_error_t err;
874  unsigned char *frame = NULL;
875  size_t nframe = (nbits+7) / 8;
876  int i;
877  size_t n;
878  unsigned char *p;
879
880  if (valuelen + 7 > nframe || !nframe)
881    {
882      /* Can't encode a VALUELEN value in a NFRAME bytes frame.  */
883      return GPG_ERR_TOO_SHORT; /* The key is too short.  */
884    }
885
886  if ( !(frame = gcry_malloc_secure (nframe)))
887    return gpg_err_code_from_syserror ();
888
889  n = 0;
890  frame[n++] = 0;
891  frame[n++] = 2; /* block type */
892  i = nframe - 3 - valuelen;
893  gcry_assert (i > 0);
894
895  if (random_override)
896    {
897      int j;
898
899      if (random_override_len != i)
900        {
901          gcry_free (frame);
902          return GPG_ERR_INV_ARG;
903        }
904      /* Check that random does not include a zero byte.  */
905      for (j=0; j < random_override_len; j++)
906        if (!random_override[j])
907          {
908            gcry_free (frame);
909            return GPG_ERR_INV_ARG;
910          }
911      memcpy (frame + n, random_override, random_override_len);
912      n += random_override_len;
913    }
914  else
915    {
916      p = gcry_random_bytes_secure (i, GCRY_STRONG_RANDOM);
917      /* Replace zero bytes by new values. */
918      for (;;)
919        {
920          int j, k;
921          unsigned char *pp;
922
923          /* Count the zero bytes. */
924          for (j=k=0; j < i; j++)
925            {
926              if (!p[j])
927                k++;
928            }
929          if (!k)
930            break; /* Okay: no (more) zero bytes. */
931
932          k += k/128 + 3; /* Better get some more. */
933          pp = gcry_random_bytes_secure (k, GCRY_STRONG_RANDOM);
934          for (j=0; j < i && k; )
935            {
936              if (!p[j])
937                p[j] = pp[--k];
938              if (p[j])
939                j++;
940            }
941          gcry_free (pp);
942        }
943      memcpy (frame+n, p, i);
944      n += i;
945      gcry_free (p);
946    }
947
948  frame[n++] = 0;
949  memcpy (frame+n, value, valuelen);
950  n += valuelen;
951  gcry_assert (n == nframe);
952
953  err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe);
954  if (err)
955    rc = gcry_err_code (err);
956  else if (DBG_CIPHER)
957    log_mpidump ("PKCS#1 block type 2 encoded data", *r_result);
958  gcry_free (frame);
959
960  return rc;
961}
962
963
964/* Decode a plaintext in VALUE assuming pkcs#1 block type 2 padding.
965   NBITS is the size of the secret key.  On success the result is
966   stored as a newly allocated buffer at R_RESULT and its valid length at
967   R_RESULTLEN.  On error NULL is stored at R_RESULT.  */
968static gcry_err_code_t
969pkcs1_decode_for_encryption (unsigned char **r_result, size_t *r_resultlen,
970                             unsigned int nbits, gcry_mpi_t value)
971{
972  gcry_error_t err;
973  unsigned char *frame = NULL;
974  size_t nframe = (nbits+7) / 8;
975  size_t n;
976
977  *r_result = NULL;
978
979  if ( !(frame = gcry_malloc_secure (nframe)))
980    return gpg_err_code_from_syserror ();
981
982  err = gcry_mpi_print (GCRYMPI_FMT_USG, frame, nframe, &n, value);
983  if (err)
984    {
985      gcry_free (frame);
986      return gcry_err_code (err);
987    }
988
989  nframe = n; /* Set NFRAME to the actual length.  */
990
991  /* FRAME = 0x00 || 0x02 || PS || 0x00 || M
992
993     pkcs#1 requires that the first byte is zero.  Our MPIs usually
994     strip leading zero bytes; thus we are not able to detect them.
995     However due to the way gcry_mpi_print is implemented we may see
996     leading zero bytes nevertheless.  We handle this by making the
997     first zero byte optional.  */
998  if (nframe < 4)
999    {
1000      gcry_free (frame);
1001      return GPG_ERR_ENCODING_PROBLEM;  /* Too short.  */
1002    }
1003  n = 0;
1004  if (!frame[0])
1005    n++;
1006  if (frame[n++] != 0x02)
1007    {
1008      gcry_free (frame);
1009      return GPG_ERR_ENCODING_PROBLEM;  /* Wrong block type.  */
1010    }
1011
1012  /* Skip the non-zero random bytes and the terminating zero byte.  */
1013  for (; n < nframe && frame[n] != 0x00; n++)
1014    ;
1015  if (n+1 >= nframe)
1016    {
1017      gcry_free (frame);
1018      return GPG_ERR_ENCODING_PROBLEM; /* No zero byte.  */
1019    }
1020  n++; /* Skip the zero byte.  */
1021
1022  /* To avoid an extra allocation we reuse the frame buffer.  The only
1023     caller of this function will anyway free the result soon.  */
1024  memmove (frame, frame + n, nframe - n);
1025  *r_result = frame;
1026  *r_resultlen = nframe - n;
1027
1028  if (DBG_CIPHER)
1029    log_printhex ("value extracted from PKCS#1 block type 2 encoded data:",
1030                  *r_result, *r_resultlen);
1031
1032  return 0;
1033}
1034
1035
1036/* Encode {VALUE,VALUELEN} for an NBITS keys and hash algorith ALGO
1037   using the pkcs#1 block type 1 padding.  On success the result is
1038   stored as a new MPI at R_RESULT.  On error the value at R_RESULT is
1039   undefined.
1040
1041   We encode the value in this way:
1042
1043     0  1  PAD(n bytes)  0  ASN(asnlen bytes) VALUE(valuelen bytes)
1044
1045   0   is a marker we unfortunately can't encode because we return an
1046       MPI which strips all leading zeroes.
1047   1   is the block type.
1048   PAD consists of 0xff bytes.
1049   0   marks the end of the padding.
1050   ASN is the DER encoding of the hash algorithm; along with the VALUE
1051       it yields a valid DER encoding.
1052
1053   (Note that PGP prior to version 2.3 encoded the message digest as:
1054      0   1   MD(16 bytes)   0   PAD(n bytes)   1
1055    The MD is always 16 bytes here because it's always MD5.  GnuPG
1056    does not not support pre-v2.3 signatures, but I'm including this
1057    comment so the information is easily found if needed.)
1058*/
1059static gcry_err_code_t
1060pkcs1_encode_for_signature (gcry_mpi_t *r_result, unsigned int nbits,
1061			    const unsigned char *value, size_t valuelen,
1062			    int algo)
1063{
1064  gcry_err_code_t rc = 0;
1065  gcry_error_t err;
1066  byte asn[100];
1067  byte *frame = NULL;
1068  size_t nframe = (nbits+7) / 8;
1069  int i;
1070  size_t n;
1071  size_t asnlen, dlen;
1072
1073  asnlen = DIM(asn);
1074  dlen = gcry_md_get_algo_dlen (algo);
1075
1076  if (gcry_md_algo_info (algo, GCRYCTL_GET_ASNOID, asn, &asnlen))
1077    {
1078      /* We don't have yet all of the above algorithms.  */
1079      return GPG_ERR_NOT_IMPLEMENTED;
1080    }
1081
1082  if ( valuelen != dlen )
1083    {
1084      /* Hash value does not match the length of digest for
1085         the given algorithm.  */
1086      return GPG_ERR_CONFLICT;
1087    }
1088
1089  if ( !dlen || dlen + asnlen + 4 > nframe)
1090    {
1091      /* Can't encode an DLEN byte digest MD into an NFRAME byte
1092         frame.  */
1093      return GPG_ERR_TOO_SHORT;
1094    }
1095
1096  if ( !(frame = gcry_malloc (nframe)) )
1097    return gpg_err_code_from_syserror ();
1098
1099  /* Assemble the pkcs#1 block type 1. */
1100  n = 0;
1101  frame[n++] = 0;
1102  frame[n++] = 1; /* block type */
1103  i = nframe - valuelen - asnlen - 3 ;
1104  gcry_assert (i > 1);
1105  memset (frame+n, 0xff, i );
1106  n += i;
1107  frame[n++] = 0;
1108  memcpy (frame+n, asn, asnlen);
1109  n += asnlen;
1110  memcpy (frame+n, value, valuelen );
1111  n += valuelen;
1112  gcry_assert (n == nframe);
1113
1114  /* Convert it into an MPI. */
1115  err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, n, &nframe);
1116  if (err)
1117    rc = gcry_err_code (err);
1118  else if (DBG_CIPHER)
1119    log_mpidump ("PKCS#1 block type 1 encoded data", *r_result);
1120  gcry_free (frame);
1121
1122  return rc;
1123}
1124
1125
1126/* Mask generation function for OAEP.  See RFC-3447 B.2.1.  */
1127static gcry_err_code_t
1128mgf1 (unsigned char *output, size_t outlen, unsigned char *seed, size_t seedlen,
1129      int algo)
1130{
1131  size_t dlen, nbytes, n;
1132  int idx;
1133  gcry_md_hd_t hd;
1134  gcry_error_t err;
1135
1136  err = gcry_md_open (&hd, algo, 0);
1137  if (err)
1138    return gpg_err_code (err);
1139
1140  dlen = gcry_md_get_algo_dlen (algo);
1141
1142  /* We skip step 1 which would be assert(OUTLEN <= 2^32).  The loop
1143     in step 3 is merged with step 4 by concatenating no more octets
1144     than what would fit into OUTPUT.  The ceiling for the counter IDX
1145     is implemented indirectly.  */
1146  nbytes = 0;  /* Step 2.  */
1147  idx = 0;
1148  while ( nbytes < outlen )
1149    {
1150      unsigned char c[4], *digest;
1151
1152      if (idx)
1153        gcry_md_reset (hd);
1154
1155      c[0] = (idx >> 24) & 0xFF;
1156      c[1] = (idx >> 16) & 0xFF;
1157      c[2] = (idx >> 8) & 0xFF;
1158      c[3] = idx & 0xFF;
1159      idx++;
1160
1161      gcry_md_write (hd, seed, seedlen);
1162      gcry_md_write (hd, c, 4);
1163      digest = gcry_md_read (hd, 0);
1164
1165      n = (outlen - nbytes < dlen)? (outlen - nbytes) : dlen;
1166      memcpy (output+nbytes, digest, n);
1167      nbytes += n;
1168    }
1169
1170  gcry_md_close (hd);
1171  return GPG_ERR_NO_ERROR;
1172}
1173
1174
1175/* RFC-3447 (pkcs#1 v2.1) OAEP encoding.  NBITS is the length of the
1176   key measured in bits.  ALGO is the hash function; it must be a
1177   valid and usable algorithm.  {VALUE,VALUELEN} is the message to
1178   encrypt.  {LABEL,LABELLEN} is the optional label to be associated
1179   with the message, if LABEL is NULL the default is to use the empty
1180   string as label.  On success the encoded ciphertext is returned at
1181   R_RESULT.
1182
1183   If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as
1184   the seed instead of using a random string for it.  This feature is
1185   only useful for regression tests.
1186
1187   Here is figure 1 from the RFC depicting the process:
1188
1189                             +----------+---------+-------+
1190                        DB = |  lHash   |    PS   |   M   |
1191                             +----------+---------+-------+
1192                                            |
1193                  +----------+              V
1194                  |   seed   |--> MGF ---> xor
1195                  +----------+              |
1196                        |                   |
1197               +--+     V                   |
1198               |00|    xor <----- MGF <-----|
1199               +--+     |                   |
1200                 |      |                   |
1201                 V      V                   V
1202               +--+----------+----------------------------+
1203         EM =  |00|maskedSeed|          maskedDB          |
1204               +--+----------+----------------------------+
1205  */
1206static gcry_err_code_t
1207oaep_encode (gcry_mpi_t *r_result, unsigned int nbits, int algo,
1208             const unsigned char *value, size_t valuelen,
1209             const unsigned char *label, size_t labellen,
1210             const void *random_override, size_t random_override_len)
1211{
1212  gcry_err_code_t rc = 0;
1213  gcry_error_t err;
1214  unsigned char *frame = NULL;
1215  size_t nframe = (nbits+7) / 8;
1216  unsigned char *p;
1217  size_t hlen;
1218  size_t n;
1219
1220  *r_result = NULL;
1221
1222  /* Set defaults for LABEL.  */
1223  if (!label || !labellen)
1224    {
1225      label = (const unsigned char*)"";
1226      labellen = 0;
1227    }
1228
1229  hlen = gcry_md_get_algo_dlen (algo);
1230
1231  /* We skip step 1a which would be to check that LABELLEN is not
1232     greater than 2^61-1.  See rfc-3447 7.1.1. */
1233
1234  /* Step 1b.  Note that the obsolete rfc-2437 uses the check:
1235     valuelen > nframe - 2 * hlen - 1 .  */
1236  if (valuelen > nframe - 2 * hlen - 2 || !nframe)
1237    {
1238      /* Can't encode a VALUELEN value in a NFRAME bytes frame. */
1239      return GPG_ERR_TOO_SHORT; /* The key is too short.  */
1240    }
1241
1242  /* Allocate the frame.  */
1243  frame = gcry_calloc_secure (1, nframe);
1244  if (!frame)
1245    return gpg_err_code_from_syserror ();
1246
1247  /* Step 2a: Compute the hash of the label.  We store it in the frame
1248     where later the maskedDB will commence.  */
1249  gcry_md_hash_buffer (algo, frame + 1 + hlen, label, labellen);
1250
1251  /* Step 2b: Set octet string to zero.  */
1252  /* This has already been done while allocating FRAME.  */
1253
1254  /* Step 2c: Create DB by concatenating lHash, PS, 0x01 and M.  */
1255  n = nframe - valuelen - 1;
1256  frame[n] = 0x01;
1257  memcpy (frame + n + 1, value, valuelen);
1258
1259  /* Step 3d: Generate seed.  We store it where the maskedSeed will go
1260     later. */
1261  if (random_override)
1262    {
1263      if (random_override_len != hlen)
1264        {
1265          gcry_free (frame);
1266          return GPG_ERR_INV_ARG;
1267        }
1268      memcpy (frame + 1, random_override, hlen);
1269    }
1270  else
1271    gcry_randomize (frame + 1, hlen, GCRY_STRONG_RANDOM);
1272
1273  /* Step 2e and 2f: Create maskedDB.  */
1274  {
1275    unsigned char *dmask;
1276
1277    dmask = gcry_malloc_secure (nframe - hlen - 1);
1278    if (!dmask)
1279      {
1280        rc = gpg_err_code_from_syserror ();
1281        gcry_free (frame);
1282        return rc;
1283      }
1284    rc = mgf1 (dmask, nframe - hlen - 1, frame+1, hlen, algo);
1285    if (rc)
1286      {
1287        gcry_free (dmask);
1288        gcry_free (frame);
1289        return rc;
1290      }
1291    for (n = 1 + hlen, p = dmask; n < nframe; n++)
1292      frame[n] ^= *p++;
1293    gcry_free (dmask);
1294  }
1295
1296  /* Step 2g and 2h: Create maskedSeed.  */
1297  {
1298    unsigned char *smask;
1299
1300    smask = gcry_malloc_secure (hlen);
1301    if (!smask)
1302      {
1303        rc = gpg_err_code_from_syserror ();
1304        gcry_free (frame);
1305        return rc;
1306      }
1307    rc = mgf1 (smask, hlen, frame + 1 + hlen, nframe - hlen - 1, algo);
1308    if (rc)
1309      {
1310        gcry_free (smask);
1311        gcry_free (frame);
1312        return rc;
1313      }
1314    for (n = 1, p = smask; n < 1 + hlen; n++)
1315      frame[n] ^= *p++;
1316    gcry_free (smask);
1317  }
1318
1319  /* Step 2i: Concatenate 0x00, maskedSeed and maskedDB.  */
1320  /* This has already been done by using in-place operations.  */
1321
1322  /* Convert the stuff into an MPI as expected by the caller.  */
1323  err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, frame, nframe, NULL);
1324  if (err)
1325    rc = gcry_err_code (err);
1326  else if (DBG_CIPHER)
1327    log_mpidump ("OAEP encoded data", *r_result);
1328  gcry_free (frame);
1329
1330  return rc;
1331}
1332
1333
1334/* RFC-3447 (pkcs#1 v2.1) OAEP decoding.  NBITS is the length of the
1335   key measured in bits.  ALGO is the hash function; it must be a
1336   valid and usable algorithm.  VALUE is the raw decrypted message
1337   {LABEL,LABELLEN} is the optional label to be associated with the
1338   message, if LABEL is NULL the default is to use the empty string as
1339   label.  On success the plaintext is returned as a newly allocated
1340   buffer at R_RESULT; its valid length is stored at R_RESULTLEN.  On
1341   error NULL is stored at R_RESULT.  */
1342static gcry_err_code_t
1343oaep_decode (unsigned char **r_result, size_t *r_resultlen,
1344             unsigned int nbits, int algo,
1345             gcry_mpi_t value, const unsigned char *label, size_t labellen)
1346{
1347  gcry_err_code_t rc;
1348  unsigned char *frame = NULL; /* Encoded messages (EM).  */
1349  unsigned char *masked_seed;  /* Points into FRAME.  */
1350  unsigned char *masked_db;    /* Points into FRAME.  */
1351  unsigned char *seed = NULL;  /* Allocated space for the seed and DB.  */
1352  unsigned char *db;           /* Points into SEED.  */
1353  unsigned char *lhash = NULL; /* Hash of the label.  */
1354  size_t nframe;               /* Length of the ciphertext (EM).  */
1355  size_t hlen;                 /* Length of the hash digest.  */
1356  size_t db_len;               /* Length of DB and masked_db.  */
1357  size_t nkey = (nbits+7)/8;   /* Length of the key in bytes.  */
1358  int failed = 0;              /* Error indicator.  */
1359  size_t n;
1360
1361  *r_result = NULL;
1362
1363  /* This code is implemented as described by rfc-3447 7.1.2.  */
1364
1365  /* Set defaults for LABEL.  */
1366  if (!label || !labellen)
1367    {
1368      label = (const unsigned char*)"";
1369      labellen = 0;
1370    }
1371
1372  /* Get the length of the digest.  */
1373  hlen = gcry_md_get_algo_dlen (algo);
1374
1375  /* Hash the label right away.  */
1376  lhash = gcry_malloc (hlen);
1377  if (!lhash)
1378    return gpg_err_code_from_syserror ();
1379  gcry_md_hash_buffer (algo, lhash, label, labellen);
1380
1381  /* Turn the MPI into an octet string.  If the octet string is
1382     shorter than the key we pad it to the left with zeroes.  This may
1383     happen due to the leading zero in OAEP frames and due to the
1384     following random octets (seed^mask) which may have leading zero
1385     bytes.  This all is needed to cope with our leading zeroes
1386     suppressing MPI implementation.  The code implictly implements
1387     Step 1b (bail out if NFRAME != N).  */
1388  rc = octet_string_from_mpi (&frame, NULL, value, nkey);
1389  if (rc)
1390    {
1391      gcry_free (lhash);
1392      return GPG_ERR_ENCODING_PROBLEM;
1393    }
1394  nframe = nkey;
1395
1396  /* Step 1c: Check that the key is long enough.  */
1397  if ( nframe < 2 * hlen + 2 )
1398    {
1399      gcry_free (frame);
1400      gcry_free (lhash);
1401      return GPG_ERR_ENCODING_PROBLEM;
1402    }
1403
1404  /* Step 2 has already been done by the caller and the
1405     gcry_mpi_aprint above.  */
1406
1407  /* Allocate space for SEED and DB.  */
1408  seed = gcry_malloc_secure (nframe - 1);
1409  if (!seed)
1410    {
1411      rc = gpg_err_code_from_syserror ();
1412      gcry_free (frame);
1413      gcry_free (lhash);
1414      return rc;
1415    }
1416  db = seed + hlen;
1417
1418  /* To avoid choosen ciphertext attacks from now on we make sure to
1419     run all code even in the error case; this avoids possible timing
1420     attacks as described by Manger.  */
1421
1422  /* Step 3a: Hash the label.  */
1423  /* This has already been done.  */
1424
1425  /* Step 3b: Separate the encoded message.  */
1426  masked_seed = frame + 1;
1427  masked_db   = frame + 1 + hlen;
1428  db_len      = nframe - 1 - hlen;
1429
1430  /* Step 3c and 3d: seed = maskedSeed ^ mgf(maskedDB, hlen).  */
1431  if (mgf1 (seed, hlen, masked_db, db_len, algo))
1432    failed = 1;
1433  for (n = 0; n < hlen; n++)
1434    seed[n] ^= masked_seed[n];
1435
1436  /* Step 3e and 3f: db = maskedDB ^ mgf(seed, db_len).  */
1437  if (mgf1 (db, db_len, seed, hlen, algo))
1438    failed = 1;
1439  for (n = 0; n < db_len; n++)
1440    db[n] ^= masked_db[n];
1441
1442  /* Step 3g: Check lhash, an possible empty padding string terminated
1443     by 0x01 and the first byte of EM being 0.  */
1444  if (memcmp (lhash, db, hlen))
1445    failed = 1;
1446  for (n = hlen; n < db_len; n++)
1447    if (db[n] == 0x01)
1448      break;
1449  if (n == db_len)
1450    failed = 1;
1451  if (frame[0])
1452    failed = 1;
1453
1454  gcry_free (lhash);
1455  gcry_free (frame);
1456  if (failed)
1457    {
1458      gcry_free (seed);
1459      return GPG_ERR_ENCODING_PROBLEM;
1460    }
1461
1462  /* Step 4: Output M.  */
1463  /* To avoid an extra allocation we reuse the seed buffer.  The only
1464     caller of this function will anyway free the result soon.  */
1465  n++;
1466  memmove (seed, db + n, db_len - n);
1467  *r_result = seed;
1468  *r_resultlen = db_len - n;
1469  seed = NULL;
1470
1471  if (DBG_CIPHER)
1472    log_printhex ("value extracted from OAEP encoded data:",
1473                  *r_result, *r_resultlen);
1474
1475  return 0;
1476}
1477
1478
1479/* RFC-3447 (pkcs#1 v2.1) PSS encoding.  Encode {VALUE,VALUELEN} for
1480   an NBITS key.  Note that VALUE is already the mHash from the
1481   picture below.  ALGO is a valid hash algorithm and SALTLEN is the
1482   length of salt to be used.  On success the result is stored as a
1483   new MPI at R_RESULT.  On error the value at R_RESULT is undefined.
1484
1485   If {RANDOM_OVERRIDE, RANDOM_OVERRIDE_LEN} is given it is used as
1486   the salt instead of using a random string for the salt.  This
1487   feature is only useful for regression tests.
1488
1489   Here is figure 2 from the RFC (errata 595 applied) depicting the
1490   process:
1491
1492                                  +-----------+
1493                                  |     M     |
1494                                  +-----------+
1495                                        |
1496                                        V
1497                                      Hash
1498                                        |
1499                                        V
1500                          +--------+----------+----------+
1501                     M' = |Padding1|  mHash   |   salt   |
1502                          +--------+----------+----------+
1503                                         |
1504               +--------+----------+     V
1505         DB =  |Padding2| salt     |   Hash
1506               +--------+----------+     |
1507                         |               |
1508                         V               |    +----+
1509                        xor <--- MGF <---|    |0xbc|
1510                         |               |    +----+
1511                         |               |      |
1512                         V               V      V
1513               +-------------------+----------+----+
1514         EM =  |    maskedDB       |     H    |0xbc|
1515               +-------------------+----------+----+
1516
1517  */
1518static gcry_err_code_t
1519pss_encode (gcry_mpi_t *r_result, unsigned int nbits, int algo,
1520	    const unsigned char *value, size_t valuelen, int saltlen,
1521            const void *random_override, size_t random_override_len)
1522{
1523  gcry_err_code_t rc = 0;
1524  gcry_error_t err;
1525  size_t hlen;                 /* Length of the hash digest.  */
1526  unsigned char *em = NULL;    /* Encoded message.  */
1527  size_t emlen = (nbits+7)/8;  /* Length in bytes of EM.  */
1528  unsigned char *h;            /* Points into EM.  */
1529  unsigned char *buf = NULL;   /* Help buffer.  */
1530  size_t buflen;               /* Length of BUF.  */
1531  unsigned char *mhash;        /* Points into BUF.  */
1532  unsigned char *salt;         /* Points into BUF.  */
1533  unsigned char *dbmask;       /* Points into BUF.  */
1534  unsigned char *p;
1535  size_t n;
1536
1537  /* This code is implemented as described by rfc-3447 9.1.1.  */
1538
1539  /* Get the length of the digest.  */
1540  hlen = gcry_md_get_algo_dlen (algo);
1541  gcry_assert (hlen);  /* We expect a valid ALGO here.  */
1542
1543  /* Allocate a help buffer and setup some pointers.  */
1544  buflen = 8 + hlen + saltlen + (emlen - hlen - 1);
1545  buf = gcry_malloc (buflen);
1546  if (!buf)
1547    {
1548      rc = gpg_err_code_from_syserror ();
1549      goto leave;
1550    }
1551  mhash = buf + 8;
1552  salt  = mhash + hlen;
1553  dbmask= salt + saltlen;
1554
1555  /* Step 2: That would be: mHash = Hash(M) but our input is already
1556     mHash thus we do only a consistency check and copy to MHASH.  */
1557  if (valuelen != hlen)
1558    {
1559      rc = GPG_ERR_INV_LENGTH;
1560      goto leave;
1561    }
1562  memcpy (mhash, value, hlen);
1563
1564  /* Step 3: Check length constraints.  */
1565  if (emlen < hlen + saltlen + 2)
1566    {
1567      rc = GPG_ERR_TOO_SHORT;
1568      goto leave;
1569    }
1570
1571  /* Allocate space for EM.  */
1572  em = gcry_malloc (emlen);
1573  if (!em)
1574    {
1575      rc = gpg_err_code_from_syserror ();
1576      goto leave;
1577    }
1578  h = em + emlen - 1 - hlen;
1579
1580  /* Step 4: Create a salt.  */
1581  if (saltlen)
1582    {
1583      if (random_override)
1584        {
1585          if (random_override_len != saltlen)
1586            {
1587              rc = GPG_ERR_INV_ARG;
1588              goto leave;
1589            }
1590          memcpy (salt, random_override, saltlen);
1591        }
1592      else
1593        gcry_randomize (salt, saltlen, GCRY_STRONG_RANDOM);
1594    }
1595
1596  /* Step 5 and 6: M' = Hash(Padding1 || mHash || salt).  */
1597  memset (buf, 0, 8);  /* Padding.  */
1598  gcry_md_hash_buffer (algo, h, buf, 8 + hlen + saltlen);
1599
1600  /* Step 7 and 8: DB = PS || 0x01 || salt.  */
1601  /* Note that we use EM to store DB and later Xor in-place.  */
1602  p = em + emlen - 1 - hlen - saltlen - 1;
1603  memset (em, 0, p - em);
1604  *p++ = 0x01;
1605  memcpy (p, salt, saltlen);
1606
1607  /* Step 9: dbmask = MGF(H, emlen - hlen - 1).  */
1608  mgf1 (dbmask, emlen - hlen - 1, h, hlen, algo);
1609
1610  /* Step 10: maskedDB = DB ^ dbMask */
1611  for (n = 0, p = dbmask; n < emlen - hlen - 1; n++, p++)
1612    em[n] ^= *p;
1613
1614  /* Step 11: Set the leftmost bits to zero.  */
1615  em[0] &= 0xFF >> (8 * emlen - nbits);
1616
1617  /* Step 12: EM = maskedDB || H || 0xbc.  */
1618  em[emlen-1] = 0xbc;
1619
1620  /* Convert EM into an MPI.  */
1621  err = gcry_mpi_scan (r_result, GCRYMPI_FMT_USG, em, emlen, NULL);
1622  if (err)
1623    rc = gcry_err_code (err);
1624  else if (DBG_CIPHER)
1625    log_mpidump ("PSS encoded data", *r_result);
1626
1627 leave:
1628  if (em)
1629    {
1630      wipememory (em, emlen);
1631      gcry_free (em);
1632    }
1633  if (buf)
1634    {
1635      wipememory (buf, buflen);
1636      gcry_free (buf);
1637    }
1638  return rc;
1639}
1640
1641
1642/* Verify a signature assuming PSS padding.  VALUE is the hash of the
1643   message (mHash) encoded as an MPI; its length must match the digest
1644   length of ALGO.  ENCODED is the output of the RSA public key
1645   function (EM).  NBITS is the size of the public key.  ALGO is the
1646   hash algorithm and SALTLEN is the length of the used salt.  The
1647   function returns 0 on success or on error code.  */
1648static gcry_err_code_t
1649pss_verify (gcry_mpi_t value, gcry_mpi_t encoded, unsigned int nbits, int algo,
1650            size_t saltlen)
1651{
1652  gcry_err_code_t rc = 0;
1653  size_t hlen;                 /* Length of the hash digest.  */
1654  unsigned char *em = NULL;    /* Encoded message.  */
1655  size_t emlen = (nbits+7)/8;  /* Length in bytes of EM.  */
1656  unsigned char *salt;         /* Points into EM.  */
1657  unsigned char *h;            /* Points into EM.  */
1658  unsigned char *buf = NULL;   /* Help buffer.  */
1659  size_t buflen;               /* Length of BUF.  */
1660  unsigned char *dbmask;       /* Points into BUF.  */
1661  unsigned char *mhash;        /* Points into BUF.  */
1662  unsigned char *p;
1663  size_t n;
1664
1665  /* This code is implemented as described by rfc-3447 9.1.2.  */
1666
1667  /* Get the length of the digest.  */
1668  hlen = gcry_md_get_algo_dlen (algo);
1669  gcry_assert (hlen);  /* We expect a valid ALGO here.  */
1670
1671  /* Allocate a help buffer and setup some pointers.
1672     This buffer is used for two purposes:
1673        +------------------------------+-------+
1674     1. | dbmask                       | mHash |
1675        +------------------------------+-------+
1676           emlen - hlen - 1              hlen
1677
1678        +----------+-------+---------+-+-------+
1679     2. | padding1 | mHash | salt    | | mHash |
1680        +----------+-------+---------+-+-------+
1681             8       hlen    saltlen     hlen
1682  */
1683  buflen = 8 + hlen + saltlen;
1684  if (buflen < emlen - hlen - 1)
1685    buflen = emlen - hlen - 1;
1686  buflen += hlen;
1687  buf = gcry_malloc (buflen);
1688  if (!buf)
1689    {
1690      rc = gpg_err_code_from_syserror ();
1691      goto leave;
1692    }
1693  dbmask = buf;
1694  mhash = buf + buflen - hlen;
1695
1696  /* Step 2: That would be: mHash = Hash(M) but our input is already
1697     mHash thus we only need to convert VALUE into MHASH.  */
1698  rc = octet_string_from_mpi (NULL, mhash, value, hlen);
1699  if (rc)
1700    goto leave;
1701
1702  /* Convert the signature into an octet string.  */
1703  rc = octet_string_from_mpi (&em, NULL, encoded, emlen);
1704  if (rc)
1705    goto leave;
1706
1707  /* Step 3: Check length of EM.  Because we internally use MPI
1708     functions we can't do this properly; EMLEN is always the length
1709     of the key because octet_string_from_mpi needs to left pad the
1710     result with zero to cope with the fact that our MPIs suppress all
1711     leading zeroes.  Thus what we test here are merely the digest and
1712     salt lengths to the key.  */
1713  if (emlen < hlen + saltlen + 2)
1714    {
1715      rc = GPG_ERR_TOO_SHORT; /* For the hash and saltlen.  */
1716      goto leave;
1717    }
1718
1719  /* Step 4: Check last octet.  */
1720  if (em[emlen - 1] != 0xbc)
1721    {
1722      rc = GPG_ERR_BAD_SIGNATURE;
1723      goto leave;
1724    }
1725
1726  /* Step 5: Split EM.  */
1727  h = em + emlen - 1 - hlen;
1728
1729  /* Step 6: Check the leftmost bits.  */
1730  if ((em[0] & ~(0xFF >> (8 * emlen - nbits))))
1731    {
1732      rc = GPG_ERR_BAD_SIGNATURE;
1733      goto leave;
1734    }
1735
1736  /* Step 7: dbmask = MGF(H, emlen - hlen - 1).  */
1737  mgf1 (dbmask, emlen - hlen - 1, h, hlen, algo);
1738
1739  /* Step 8: maskedDB = DB ^ dbMask.  */
1740  for (n = 0, p = dbmask; n < emlen - hlen - 1; n++, p++)
1741    em[n] ^= *p;
1742
1743  /* Step 9: Set leftmost bits in DB to zero.  */
1744  em[0] &= 0xFF >> (8 * emlen - nbits);
1745
1746  /* Step 10: Check the padding of DB.  */
1747  for (n = 0; n < emlen - hlen - saltlen - 2 && !em[n]; n++)
1748    ;
1749  if (n != emlen - hlen - saltlen - 2 || em[n++] != 1)
1750    {
1751      rc = GPG_ERR_BAD_SIGNATURE;
1752      goto leave;
1753    }
1754
1755  /* Step 11: Extract salt from DB.  */
1756  salt = em + n;
1757
1758  /* Step 12:  M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */
1759  memset (buf, 0, 8);
1760  memcpy (buf+8, mhash, hlen);
1761  memcpy (buf+8+hlen, salt, saltlen);
1762
1763  /* Step 13:  H' = Hash(M').  */
1764  gcry_md_hash_buffer (algo, buf, buf, 8 + hlen + saltlen);
1765
1766  /* Step 14:  Check H == H'.   */
1767  rc = memcmp (h, buf, hlen) ? GPG_ERR_BAD_SIGNATURE : GPG_ERR_NO_ERROR;
1768
1769 leave:
1770  if (em)
1771    {
1772      wipememory (em, emlen);
1773      gcry_free (em);
1774    }
1775  if (buf)
1776    {
1777      wipememory (buf, buflen);
1778      gcry_free (buf);
1779    }
1780  return rc;
1781}
1782
1783
1784/* Callback for the pubkey algorithm code to verify PSS signatures.
1785   OPAQUE is the data provided by the actual caller.  The meaning of
1786   TMP depends on the actual algorithm (but there is only RSA); now
1787   for RSA it is the output of running the public key function on the
1788   input.  */
1789static int
1790pss_verify_cmp (void *opaque, gcry_mpi_t tmp)
1791{
1792  struct pk_encoding_ctx *ctx = opaque;
1793  gcry_mpi_t hash = ctx->verify_arg;
1794
1795  return pss_verify (hash, tmp, ctx->nbits - 1, ctx->hash_algo, ctx->saltlen);
1796}
1797
1798
1799/* Internal function.   */
1800static gcry_err_code_t
1801sexp_elements_extract (gcry_sexp_t key_sexp, const char *element_names,
1802		       gcry_mpi_t *elements, const char *algo_name)
1803{
1804  gcry_err_code_t err = 0;
1805  int i, idx;
1806  const char *name;
1807  gcry_sexp_t list;
1808
1809  for (name = element_names, idx = 0; *name && !err; name++, idx++)
1810    {
1811      list = gcry_sexp_find_token (key_sexp, name, 1);
1812      if (!list)
1813	elements[idx] = NULL;
1814      else
1815	{
1816	  elements[idx] = gcry_sexp_nth_mpi (list, 1, GCRYMPI_FMT_USG);
1817	  gcry_sexp_release (list);
1818	  if (!elements[idx])
1819	    err = GPG_ERR_INV_OBJ;
1820	}
1821    }
1822
1823  if (!err)
1824    {
1825      /* Check that all elements are available.  */
1826      for (name = element_names, idx = 0; *name; name++, idx++)
1827        if (!elements[idx])
1828          break;
1829      if (*name)
1830        {
1831          err = GPG_ERR_NO_OBJ;
1832          /* Some are missing.  Before bailing out we test for
1833             optional parameters.  */
1834          if (algo_name && !strcmp (algo_name, "RSA")
1835              && !strcmp (element_names, "nedpqu") )
1836            {
1837              /* This is RSA.  Test whether we got N, E and D and that
1838                 the optional P, Q and U are all missing.  */
1839              if (elements[0] && elements[1] && elements[2]
1840                  && !elements[3] && !elements[4] && !elements[5])
1841                err = 0;
1842            }
1843        }
1844    }
1845
1846
1847  if (err)
1848    {
1849      for (i = 0; i < idx; i++)
1850        if (elements[i])
1851          gcry_free (elements[i]);
1852    }
1853  return err;
1854}
1855
1856
1857/* Internal function used for ecc.  Note, that this function makes use
1858   of its intimate knowledge about the ECC parameters from ecc.c. */
1859static gcry_err_code_t
1860sexp_elements_extract_ecc (gcry_sexp_t key_sexp, const char *element_names,
1861                           gcry_mpi_t *elements, pk_extra_spec_t *extraspec)
1862
1863{
1864  gcry_err_code_t err = 0;
1865  int idx;
1866  const char *name;
1867  gcry_sexp_t list;
1868
1869  /* Clear the array for easier error cleanup. */
1870  for (name = element_names, idx = 0; *name; name++, idx++)
1871    elements[idx] = NULL;
1872  gcry_assert (idx >= 5); /* We know that ECC has at least 5 elements
1873                             (params only) or 6 (full public key).  */
1874  if (idx == 5)
1875    elements[5] = NULL;   /* Extra clear for the params only case.  */
1876
1877
1878  /* Init the array with the available curve parameters. */
1879  for (name = element_names, idx = 0; *name && !err; name++, idx++)
1880    {
1881      list = gcry_sexp_find_token (key_sexp, name, 1);
1882      if (!list)
1883	elements[idx] = NULL;
1884      else
1885	{
1886	  elements[idx] = gcry_sexp_nth_mpi (list, 1, GCRYMPI_FMT_USG);
1887	  gcry_sexp_release (list);
1888	  if (!elements[idx])
1889            {
1890              err = GPG_ERR_INV_OBJ;
1891              goto leave;
1892            }
1893	}
1894    }
1895
1896  /* Check whether a curve parameter has been given and then fill any
1897     missing elements.  */
1898  list = gcry_sexp_find_token (key_sexp, "curve", 5);
1899  if (list)
1900    {
1901      if (extraspec->get_param)
1902        {
1903          char *curve;
1904          gcry_mpi_t params[6];
1905
1906          for (idx = 0; idx < DIM(params); idx++)
1907            params[idx] = NULL;
1908
1909          curve = _gcry_sexp_nth_string (list, 1);
1910          gcry_sexp_release (list);
1911          if (!curve)
1912            {
1913              /* No curve name given (or out of core). */
1914              err = GPG_ERR_INV_OBJ;
1915              goto leave;
1916            }
1917          err = extraspec->get_param (curve, params);
1918          gcry_free (curve);
1919          if (err)
1920            goto leave;
1921
1922          for (idx = 0; idx < DIM(params); idx++)
1923            {
1924              if (!elements[idx])
1925                elements[idx] = params[idx];
1926              else
1927                mpi_free (params[idx]);
1928            }
1929        }
1930      else
1931        {
1932          gcry_sexp_release (list);
1933          err = GPG_ERR_INV_OBJ; /* "curve" given but ECC not supported. */
1934          goto leave;
1935        }
1936    }
1937
1938  /* Check that all parameters are known.  */
1939  for (name = element_names, idx = 0; *name; name++, idx++)
1940    if (!elements[idx])
1941      {
1942        err = GPG_ERR_NO_OBJ;
1943        goto leave;
1944      }
1945
1946 leave:
1947  if (err)
1948    {
1949      for (name = element_names, idx = 0; *name; name++, idx++)
1950        if (elements[idx])
1951          gcry_free (elements[idx]);
1952    }
1953  return err;
1954}
1955
1956
1957
1958/****************
1959 * Convert a S-Exp with either a private or a public key to our
1960 * internal format. Currently we do only support the following
1961 * algorithms:
1962 *    dsa
1963 *    rsa
1964 *    openpgp-dsa
1965 *    openpgp-rsa
1966 *    openpgp-elg
1967 *    openpgp-elg-sig
1968 *    ecdsa
1969 *    ecdh
1970 * Provide a SE with the first element be either "private-key" or
1971 * or "public-key". It is followed by a list with its first element
1972 * be one of the above algorithm identifiers and the remaning
1973 * elements are pairs with parameter-id and value.
1974 * NOTE: we look through the list to find a list beginning with
1975 * "private-key" or "public-key" - the first one found is used.
1976 *
1977 * If OVERRIDE_ELEMS is not NULL those elems override the parameter
1978 * specification taken from the module.  This ise used by
1979 * gcry_pk_get_curve.
1980 *
1981 * Returns: A pointer to an allocated array of MPIs if the return value is
1982 *	    zero; the caller has to release this array.
1983 *
1984 * Example of a DSA public key:
1985 *  (private-key
1986 *    (dsa
1987 *	(p <mpi>)
1988 *	(g <mpi>)
1989 *	(y <mpi>)
1990 *	(x <mpi>)
1991 *    )
1992 *  )
1993 * The <mpi> are expected to be in GCRYMPI_FMT_USG
1994 */
1995static gcry_err_code_t
1996sexp_to_key (gcry_sexp_t sexp, int want_private, const char *override_elems,
1997             gcry_mpi_t **retarray, gcry_module_t *retalgo)
1998{
1999  gcry_err_code_t err = 0;
2000  gcry_sexp_t list, l2;
2001  char *name;
2002  const char *elems;
2003  gcry_mpi_t *array;
2004  gcry_module_t module;
2005  gcry_pk_spec_t *pubkey;
2006  pk_extra_spec_t *extraspec;
2007  int is_ecc;
2008
2009  /* Check that the first element is valid.  */
2010  list = gcry_sexp_find_token (sexp,
2011                               want_private? "private-key":"public-key", 0);
2012  if (!list)
2013    return GPG_ERR_INV_OBJ; /* Does not contain a key object.  */
2014
2015  l2 = gcry_sexp_cadr( list );
2016  gcry_sexp_release ( list );
2017  list = l2;
2018  name = _gcry_sexp_nth_string (list, 0);
2019  if (!name)
2020    {
2021      gcry_sexp_release ( list );
2022      return GPG_ERR_INV_OBJ;      /* Invalid structure of object. */
2023    }
2024
2025  ath_mutex_lock (&pubkeys_registered_lock);
2026  module = gcry_pk_lookup_name (name);
2027  ath_mutex_unlock (&pubkeys_registered_lock);
2028
2029  /* Fixme: We should make sure that an ECC key is always named "ecc"
2030     and not "ecdsa".  "ecdsa" should be used for the signature
2031     itself.  We need a function to test whether an algorithm given
2032     with a key is compatible with an application of the key (signing,
2033     encryption).  For RSA this is easy, but ECC is the first
2034     algorithm which has many flavours.  */
2035  is_ecc = ( !strcmp (name, "ecdsa")
2036             || !strcmp (name, "ecdh")
2037             || !strcmp (name, "ecc") );
2038  gcry_free (name);
2039
2040  if (!module)
2041    {
2042      gcry_sexp_release (list);
2043      return GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm. */
2044    }
2045  else
2046    {
2047      pubkey = (gcry_pk_spec_t *) module->spec;
2048      extraspec = module->extraspec;
2049    }
2050
2051  if (override_elems)
2052    elems = override_elems;
2053  else if (want_private)
2054    elems = pubkey->elements_skey;
2055  else
2056    elems = pubkey->elements_pkey;
2057  array = gcry_calloc (strlen (elems) + 1, sizeof (*array));
2058  if (!array)
2059    err = gpg_err_code_from_syserror ();
2060  if (!err)
2061    {
2062      if (is_ecc)
2063        err = sexp_elements_extract_ecc (list, elems, array, extraspec);
2064      else
2065        err = sexp_elements_extract (list, elems, array, pubkey->name);
2066    }
2067
2068  gcry_sexp_release (list);
2069
2070  if (err)
2071    {
2072      gcry_free (array);
2073
2074      ath_mutex_lock (&pubkeys_registered_lock);
2075      _gcry_module_release (module);
2076      ath_mutex_unlock (&pubkeys_registered_lock);
2077    }
2078  else
2079    {
2080      *retarray = array;
2081      *retalgo = module;
2082    }
2083
2084  return err;
2085}
2086
2087
2088static gcry_err_code_t
2089sexp_to_sig (gcry_sexp_t sexp, gcry_mpi_t **retarray,
2090	     gcry_module_t *retalgo)
2091{
2092  gcry_err_code_t err = 0;
2093  gcry_sexp_t list, l2;
2094  char *name;
2095  const char *elems;
2096  gcry_mpi_t *array;
2097  gcry_module_t module;
2098  gcry_pk_spec_t *pubkey;
2099
2100  /* Check that the first element is valid.  */
2101  list = gcry_sexp_find_token( sexp, "sig-val" , 0 );
2102  if (!list)
2103    return GPG_ERR_INV_OBJ; /* Does not contain a signature value object.  */
2104
2105  l2 = gcry_sexp_nth (list, 1);
2106  if (!l2)
2107    {
2108      gcry_sexp_release (list);
2109      return GPG_ERR_NO_OBJ;   /* No cadr for the sig object.  */
2110    }
2111  name = _gcry_sexp_nth_string (l2, 0);
2112  if (!name)
2113    {
2114      gcry_sexp_release (list);
2115      gcry_sexp_release (l2);
2116      return GPG_ERR_INV_OBJ;  /* Invalid structure of object.  */
2117    }
2118  else if (!strcmp (name, "flags"))
2119    {
2120      /* Skip flags, since they are not used but here just for the
2121	 sake of consistent S-expressions.  */
2122      gcry_free (name);
2123      gcry_sexp_release (l2);
2124      l2 = gcry_sexp_nth (list, 2);
2125      if (!l2)
2126	{
2127	  gcry_sexp_release (list);
2128	  return GPG_ERR_INV_OBJ;
2129	}
2130      name = _gcry_sexp_nth_string (l2, 0);
2131    }
2132
2133  ath_mutex_lock (&pubkeys_registered_lock);
2134  module = gcry_pk_lookup_name (name);
2135  ath_mutex_unlock (&pubkeys_registered_lock);
2136  gcry_free (name);
2137  name = NULL;
2138
2139  if (!module)
2140    {
2141      gcry_sexp_release (l2);
2142      gcry_sexp_release (list);
2143      return GPG_ERR_PUBKEY_ALGO;  /* Unknown algorithm. */
2144    }
2145  else
2146    pubkey = (gcry_pk_spec_t *) module->spec;
2147
2148  elems = pubkey->elements_sig;
2149  array = gcry_calloc (strlen (elems) + 1 , sizeof *array );
2150  if (!array)
2151    err = gpg_err_code_from_syserror ();
2152
2153  if (!err)
2154    err = sexp_elements_extract (list, elems, array, NULL);
2155
2156  gcry_sexp_release (l2);
2157  gcry_sexp_release (list);
2158
2159  if (err)
2160    {
2161      ath_mutex_lock (&pubkeys_registered_lock);
2162      _gcry_module_release (module);
2163      ath_mutex_unlock (&pubkeys_registered_lock);
2164
2165      gcry_free (array);
2166    }
2167  else
2168    {
2169      *retarray = array;
2170      *retalgo = module;
2171    }
2172
2173  return err;
2174}
2175
2176static inline int
2177get_hash_algo (const char *s, size_t n)
2178{
2179  static const struct { const char *name; int algo; } hashnames[] = {
2180    { "sha1",   GCRY_MD_SHA1 },
2181    { "md5",    GCRY_MD_MD5 },
2182    { "sha256", GCRY_MD_SHA256 },
2183    { "ripemd160", GCRY_MD_RMD160 },
2184    { "rmd160", GCRY_MD_RMD160 },
2185    { "sha384", GCRY_MD_SHA384 },
2186    { "sha512", GCRY_MD_SHA512 },
2187    { "sha224", GCRY_MD_SHA224 },
2188    { "md2",    GCRY_MD_MD2 },
2189    { "md4",    GCRY_MD_MD4 },
2190    { "tiger",  GCRY_MD_TIGER },
2191    { "haval",  GCRY_MD_HAVAL },
2192    { NULL, 0 }
2193  };
2194  int algo;
2195  int i;
2196
2197  for (i=0; hashnames[i].name; i++)
2198    {
2199      if ( strlen (hashnames[i].name) == n
2200	   && !memcmp (hashnames[i].name, s, n))
2201	break;
2202    }
2203  if (hashnames[i].name)
2204    algo = hashnames[i].algo;
2205  else
2206    {
2207      /* In case of not listed or dynamically allocated hash
2208	 algorithm we fall back to this somewhat slower
2209	 method.  Further, it also allows to use OIDs as
2210	 algorithm names. */
2211      char *tmpname;
2212
2213      tmpname = gcry_malloc (n+1);
2214      if (!tmpname)
2215	algo = 0;  /* Out of core - silently give up.  */
2216      else
2217	{
2218	  memcpy (tmpname, s, n);
2219	  tmpname[n] = 0;
2220	  algo = gcry_md_map_name (tmpname);
2221	  gcry_free (tmpname);
2222	}
2223    }
2224  return algo;
2225}
2226
2227
2228/****************
2229 * Take sexp and return an array of MPI as used for our internal decrypt
2230 * function.
2231 * s_data = (enc-val
2232 *           [(flags [raw, pkcs1, oaep, no-blinding])]
2233 *           [(hash-algo <algo>)]
2234 *           [(label <label>)]
2235 *	      (<algo>
2236 *		(<param_name1> <mpi>)
2237 *		...
2238 *		(<param_namen> <mpi>)
2239 *	      ))
2240 * HASH-ALGO and LABEL are specific to OAEP.
2241 * RET_MODERN is set to true when at least an empty flags list has been found.
2242 * CTX is used to return encoding information; it may be NULL in which
2243 * case raw encoding is used.
2244 */
2245static gcry_err_code_t
2246sexp_to_enc (gcry_sexp_t sexp, gcry_mpi_t **retarray, gcry_module_t *retalgo,
2247             int *ret_modern, int *flags, struct pk_encoding_ctx *ctx)
2248{
2249  gcry_err_code_t err = 0;
2250  gcry_sexp_t list = NULL, l2 = NULL;
2251  gcry_pk_spec_t *pubkey = NULL;
2252  gcry_module_t module = NULL;
2253  char *name = NULL;
2254  size_t n;
2255  int parsed_flags = 0;
2256  const char *elems;
2257  gcry_mpi_t *array = NULL;
2258
2259  *ret_modern = 0;
2260
2261  /* Check that the first element is valid.  */
2262  list = gcry_sexp_find_token (sexp, "enc-val" , 0);
2263  if (!list)
2264    {
2265      err = GPG_ERR_INV_OBJ; /* Does not contain an encrypted value object.  */
2266      goto leave;
2267    }
2268
2269  l2 = gcry_sexp_nth (list, 1);
2270  if (!l2)
2271    {
2272      err = GPG_ERR_NO_OBJ; /* No cdr for the data object.  */
2273      goto leave;
2274    }
2275
2276  /* Extract identifier of sublist.  */
2277  name = _gcry_sexp_nth_string (l2, 0);
2278  if (!name)
2279    {
2280      err = GPG_ERR_INV_OBJ; /* Invalid structure of object.  */
2281      goto leave;
2282    }
2283
2284  if (!strcmp (name, "flags"))
2285    {
2286      /* There is a flags element - process it.  */
2287      const char *s;
2288      int i;
2289
2290      *ret_modern = 1;
2291      for (i = gcry_sexp_length (l2) - 1; i > 0; i--)
2292        {
2293          s = gcry_sexp_nth_data (l2, i, &n);
2294          if (! s)
2295            ; /* Not a data element - ignore.  */
2296          else if (n == 3 && !memcmp (s, "raw", 3)
2297                   && ctx->encoding == PUBKEY_ENC_UNKNOWN)
2298            ctx->encoding = PUBKEY_ENC_RAW;
2299          else if (n == 5 && !memcmp (s, "pkcs1", 5)
2300                   && ctx->encoding == PUBKEY_ENC_UNKNOWN)
2301	    ctx->encoding = PUBKEY_ENC_PKCS1;
2302          else if (n == 4 && !memcmp (s, "oaep", 4)
2303                   && ctx->encoding == PUBKEY_ENC_UNKNOWN)
2304	    ctx->encoding = PUBKEY_ENC_OAEP;
2305          else if (n == 3 && !memcmp (s, "pss", 3)
2306                   && ctx->encoding == PUBKEY_ENC_UNKNOWN)
2307	    {
2308	      err = GPG_ERR_CONFLICT;
2309	      goto leave;
2310	    }
2311          else if (n == 11 && ! memcmp (s, "no-blinding", 11))
2312            parsed_flags |= PUBKEY_FLAG_NO_BLINDING;
2313          else
2314            {
2315              err = GPG_ERR_INV_FLAG;
2316              goto leave;
2317            }
2318        }
2319      gcry_sexp_release (l2);
2320
2321      /* Get the OAEP parameters HASH-ALGO and LABEL, if any. */
2322      if (ctx->encoding == PUBKEY_ENC_OAEP)
2323	{
2324	  /* Get HASH-ALGO. */
2325	  l2 = gcry_sexp_find_token (list, "hash-algo", 0);
2326	  if (l2)
2327	    {
2328	      s = gcry_sexp_nth_data (l2, 1, &n);
2329	      if (!s)
2330		err = GPG_ERR_NO_OBJ;
2331	      else
2332		{
2333		  ctx->hash_algo = get_hash_algo (s, n);
2334		  if (!ctx->hash_algo)
2335		    err = GPG_ERR_DIGEST_ALGO;
2336		}
2337	      gcry_sexp_release (l2);
2338	      if (err)
2339		goto leave;
2340	    }
2341
2342	  /* Get LABEL. */
2343	  l2 = gcry_sexp_find_token (list, "label", 0);
2344	  if (l2)
2345	    {
2346	      s = gcry_sexp_nth_data (l2, 1, &n);
2347	      if (!s)
2348		err = GPG_ERR_NO_OBJ;
2349	      else if (n > 0)
2350		{
2351		  ctx->label = gcry_malloc (n);
2352		  if (!ctx->label)
2353		    err = gpg_err_code_from_syserror ();
2354		  else
2355		    {
2356		      memcpy (ctx->label, s, n);
2357		      ctx->labellen = n;
2358		    }
2359		}
2360	      gcry_sexp_release (l2);
2361	      if (err)
2362		goto leave;
2363	    }
2364	}
2365
2366      /* Get the next which has the actual data - skip HASH-ALGO and LABEL. */
2367      for (i = 2; (l2 = gcry_sexp_nth (list, i)) != NULL; i++)
2368	{
2369	  s = gcry_sexp_nth_data (l2, 0, &n);
2370	  if (!(n == 9 && !memcmp (s, "hash-algo", 9))
2371	      && !(n == 5 && !memcmp (s, "label", 5))
2372	      && !(n == 15 && !memcmp (s, "random-override", 15)))
2373	    break;
2374	  gcry_sexp_release (l2);
2375	}
2376
2377      if (!l2)
2378        {
2379          err = GPG_ERR_NO_OBJ; /* No cdr for the data object. */
2380          goto leave;
2381        }
2382
2383      /* Extract sublist identifier.  */
2384      gcry_free (name);
2385      name = _gcry_sexp_nth_string (l2, 0);
2386      if (!name)
2387        {
2388          err = GPG_ERR_INV_OBJ; /* Invalid structure of object. */
2389          goto leave;
2390        }
2391
2392      gcry_sexp_release (list);
2393      list = l2;
2394      l2 = NULL;
2395    }
2396
2397  ath_mutex_lock (&pubkeys_registered_lock);
2398  module = gcry_pk_lookup_name (name);
2399  ath_mutex_unlock (&pubkeys_registered_lock);
2400
2401  if (!module)
2402    {
2403      err = GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm.  */
2404      goto leave;
2405    }
2406  pubkey = (gcry_pk_spec_t *) module->spec;
2407
2408  elems = pubkey->elements_enc;
2409  array = gcry_calloc (strlen (elems) + 1, sizeof (*array));
2410  if (!array)
2411    {
2412      err = gpg_err_code_from_syserror ();
2413      goto leave;
2414    }
2415
2416  err = sexp_elements_extract (list, elems, array, NULL);
2417
2418 leave:
2419  gcry_sexp_release (list);
2420  gcry_sexp_release (l2);
2421  gcry_free (name);
2422
2423  if (err)
2424    {
2425      ath_mutex_lock (&pubkeys_registered_lock);
2426      _gcry_module_release (module);
2427      ath_mutex_unlock (&pubkeys_registered_lock);
2428      gcry_free (array);
2429      gcry_free (ctx->label);
2430      ctx->label = NULL;
2431    }
2432  else
2433    {
2434      *retarray = array;
2435      *retalgo = module;
2436      *flags = parsed_flags;
2437    }
2438
2439  return err;
2440}
2441
2442/* Take the hash value and convert into an MPI, suitable for
2443   passing to the low level functions.  We currently support the
2444   old style way of passing just a MPI and the modern interface which
2445   allows to pass flags so that we can choose between raw and pkcs1
2446   padding - may be more padding options later.
2447
2448   (<mpi>)
2449   or
2450   (data
2451    [(flags [raw, pkcs1, oaep, pss, no-blinding])]
2452    [(hash <algo> <value>)]
2453    [(value <text>)]
2454    [(hash-algo <algo>)]
2455    [(label <label>)]
2456    [(salt-length <length>)]
2457    [(random-override <data>)]
2458   )
2459
2460   Either the VALUE or the HASH element must be present for use
2461   with signatures.  VALUE is used for encryption.
2462
2463   HASH-ALGO and LABEL are specific to OAEP.
2464
2465   SALT-LENGTH is for PSS.
2466
2467   RANDOM-OVERRIDE is used to replace random nonces for regression
2468   testing.  */
2469static gcry_err_code_t
2470sexp_data_to_mpi (gcry_sexp_t input, gcry_mpi_t *ret_mpi,
2471		  struct pk_encoding_ctx *ctx)
2472{
2473  gcry_err_code_t rc = 0;
2474  gcry_sexp_t ldata, lhash, lvalue;
2475  int i;
2476  size_t n;
2477  const char *s;
2478  int unknown_flag=0;
2479  int parsed_flags = 0;
2480
2481  *ret_mpi = NULL;
2482  ldata = gcry_sexp_find_token (input, "data", 0);
2483  if (!ldata)
2484    { /* assume old style */
2485      *ret_mpi = gcry_sexp_nth_mpi (input, 0, 0);
2486      return *ret_mpi ? GPG_ERR_NO_ERROR : GPG_ERR_INV_OBJ;
2487    }
2488
2489  /* see whether there is a flags object */
2490  {
2491    gcry_sexp_t lflags = gcry_sexp_find_token (ldata, "flags", 0);
2492    if (lflags)
2493      { /* parse the flags list. */
2494        for (i=gcry_sexp_length (lflags)-1; i > 0; i--)
2495          {
2496            s = gcry_sexp_nth_data (lflags, i, &n);
2497            if (!s)
2498              ; /* not a data element*/
2499            else if ( n == 3 && !memcmp (s, "raw", 3)
2500                      && ctx->encoding == PUBKEY_ENC_UNKNOWN)
2501              ctx->encoding = PUBKEY_ENC_RAW;
2502            else if ( n == 5 && !memcmp (s, "pkcs1", 5)
2503                      && ctx->encoding == PUBKEY_ENC_UNKNOWN)
2504              ctx->encoding = PUBKEY_ENC_PKCS1;
2505            else if ( n == 4 && !memcmp (s, "oaep", 4)
2506                      && ctx->encoding == PUBKEY_ENC_UNKNOWN)
2507              ctx->encoding = PUBKEY_ENC_OAEP;
2508            else if ( n == 3 && !memcmp (s, "pss", 3)
2509                      && ctx->encoding == PUBKEY_ENC_UNKNOWN)
2510              ctx->encoding = PUBKEY_ENC_PSS;
2511	    else if (n == 11 && ! memcmp (s, "no-blinding", 11))
2512	      parsed_flags |= PUBKEY_FLAG_NO_BLINDING;
2513            else
2514              unknown_flag = 1;
2515          }
2516        gcry_sexp_release (lflags);
2517      }
2518  }
2519
2520  if (ctx->encoding == PUBKEY_ENC_UNKNOWN)
2521    ctx->encoding = PUBKEY_ENC_RAW; /* default to raw */
2522
2523  /* Get HASH or MPI */
2524  lhash = gcry_sexp_find_token (ldata, "hash", 0);
2525  lvalue = lhash? NULL : gcry_sexp_find_token (ldata, "value", 0);
2526
2527  if (!(!lhash ^ !lvalue))
2528    rc = GPG_ERR_INV_OBJ; /* none or both given */
2529  else if (unknown_flag)
2530    rc = GPG_ERR_INV_FLAG;
2531  else if (ctx->encoding == PUBKEY_ENC_RAW && lvalue)
2532    {
2533      *ret_mpi = gcry_sexp_nth_mpi (lvalue, 1, GCRYMPI_FMT_USG);
2534      if (!*ret_mpi)
2535        rc = GPG_ERR_INV_OBJ;
2536    }
2537  else if (ctx->encoding == PUBKEY_ENC_PKCS1 && lvalue
2538	   && ctx->op == PUBKEY_OP_ENCRYPT)
2539    {
2540      const void * value;
2541      size_t valuelen;
2542      gcry_sexp_t list;
2543      void *random_override = NULL;
2544      size_t random_override_len = 0;
2545
2546      if ( !(value=gcry_sexp_nth_data (lvalue, 1, &valuelen)) || !valuelen )
2547        rc = GPG_ERR_INV_OBJ;
2548      else
2549        {
2550          /* Get optional RANDOM-OVERRIDE.  */
2551          list = gcry_sexp_find_token (ldata, "random-override", 0);
2552          if (list)
2553            {
2554              s = gcry_sexp_nth_data (list, 1, &n);
2555              if (!s)
2556                rc = GPG_ERR_NO_OBJ;
2557              else if (n > 0)
2558                {
2559                  random_override = gcry_malloc (n);
2560                  if (!random_override)
2561                    rc = gpg_err_code_from_syserror ();
2562                  else
2563                    {
2564                      memcpy (random_override, s, n);
2565                      random_override_len = n;
2566                    }
2567                }
2568              gcry_sexp_release (list);
2569              if (rc)
2570                goto leave;
2571            }
2572
2573          rc = pkcs1_encode_for_encryption (ret_mpi, ctx->nbits,
2574                                            value, valuelen,
2575                                            random_override,
2576                                            random_override_len);
2577          gcry_free (random_override);
2578        }
2579    }
2580  else if (ctx->encoding == PUBKEY_ENC_PKCS1 && lhash
2581	   && (ctx->op == PUBKEY_OP_SIGN || ctx->op == PUBKEY_OP_VERIFY))
2582    {
2583      if (gcry_sexp_length (lhash) != 3)
2584        rc = GPG_ERR_INV_OBJ;
2585      else if ( !(s=gcry_sexp_nth_data (lhash, 1, &n)) || !n )
2586        rc = GPG_ERR_INV_OBJ;
2587      else
2588        {
2589          const void * value;
2590          size_t valuelen;
2591
2592	  ctx->hash_algo = get_hash_algo (s, n);
2593
2594          if (!ctx->hash_algo)
2595            rc = GPG_ERR_DIGEST_ALGO;
2596          else if ( !(value=gcry_sexp_nth_data (lhash, 2, &valuelen))
2597                    || !valuelen )
2598            rc = GPG_ERR_INV_OBJ;
2599          else
2600	    rc = pkcs1_encode_for_signature (ret_mpi, ctx->nbits,
2601					     value, valuelen,
2602					     ctx->hash_algo);
2603        }
2604    }
2605  else if (ctx->encoding == PUBKEY_ENC_OAEP && lvalue
2606	   && ctx->op == PUBKEY_OP_ENCRYPT)
2607    {
2608      const void * value;
2609      size_t valuelen;
2610
2611      if ( !(value=gcry_sexp_nth_data (lvalue, 1, &valuelen)) || !valuelen )
2612	rc = GPG_ERR_INV_OBJ;
2613      else
2614	{
2615	  gcry_sexp_t list;
2616          void *random_override = NULL;
2617          size_t random_override_len = 0;
2618
2619	  /* Get HASH-ALGO. */
2620	  list = gcry_sexp_find_token (ldata, "hash-algo", 0);
2621	  if (list)
2622	    {
2623	      s = gcry_sexp_nth_data (list, 1, &n);
2624	      if (!s)
2625		rc = GPG_ERR_NO_OBJ;
2626	      else
2627		{
2628		  ctx->hash_algo = get_hash_algo (s, n);
2629		  if (!ctx->hash_algo)
2630		    rc = GPG_ERR_DIGEST_ALGO;
2631		}
2632	      gcry_sexp_release (list);
2633	      if (rc)
2634		goto leave;
2635	    }
2636
2637	  /* Get LABEL. */
2638	  list = gcry_sexp_find_token (ldata, "label", 0);
2639	  if (list)
2640	    {
2641	      s = gcry_sexp_nth_data (list, 1, &n);
2642	      if (!s)
2643		rc = GPG_ERR_NO_OBJ;
2644	      else if (n > 0)
2645		{
2646		  ctx->label = gcry_malloc (n);
2647		  if (!ctx->label)
2648		    rc = gpg_err_code_from_syserror ();
2649		  else
2650		    {
2651		      memcpy (ctx->label, s, n);
2652		      ctx->labellen = n;
2653		    }
2654		}
2655	      gcry_sexp_release (list);
2656	      if (rc)
2657		goto leave;
2658	    }
2659          /* Get optional RANDOM-OVERRIDE.  */
2660          list = gcry_sexp_find_token (ldata, "random-override", 0);
2661          if (list)
2662            {
2663              s = gcry_sexp_nth_data (list, 1, &n);
2664              if (!s)
2665                rc = GPG_ERR_NO_OBJ;
2666              else if (n > 0)
2667                {
2668                  random_override = gcry_malloc (n);
2669                  if (!random_override)
2670                    rc = gpg_err_code_from_syserror ();
2671                  else
2672                    {
2673                      memcpy (random_override, s, n);
2674                      random_override_len = n;
2675                    }
2676                }
2677              gcry_sexp_release (list);
2678              if (rc)
2679                goto leave;
2680            }
2681
2682	  rc = oaep_encode (ret_mpi, ctx->nbits, ctx->hash_algo,
2683			    value, valuelen,
2684			    ctx->label, ctx->labellen,
2685                            random_override, random_override_len);
2686
2687          gcry_free (random_override);
2688	}
2689    }
2690  else if (ctx->encoding == PUBKEY_ENC_PSS && lhash
2691	   && ctx->op == PUBKEY_OP_SIGN)
2692    {
2693      if (gcry_sexp_length (lhash) != 3)
2694        rc = GPG_ERR_INV_OBJ;
2695      else if ( !(s=gcry_sexp_nth_data (lhash, 1, &n)) || !n )
2696        rc = GPG_ERR_INV_OBJ;
2697      else
2698        {
2699          const void * value;
2700          size_t valuelen;
2701          void *random_override = NULL;
2702          size_t random_override_len = 0;
2703
2704	  ctx->hash_algo = get_hash_algo (s, n);
2705
2706          if (!ctx->hash_algo)
2707            rc = GPG_ERR_DIGEST_ALGO;
2708          else if ( !(value=gcry_sexp_nth_data (lhash, 2, &valuelen))
2709                    || !valuelen )
2710            rc = GPG_ERR_INV_OBJ;
2711          else
2712	    {
2713	      gcry_sexp_t list;
2714
2715	      /* Get SALT-LENGTH. */
2716	      list = gcry_sexp_find_token (ldata, "salt-length", 0);
2717	      if (list)
2718		{
2719		  s = gcry_sexp_nth_data (list, 1, &n);
2720		  if (!s)
2721		    {
2722		      rc = GPG_ERR_NO_OBJ;
2723		      goto leave;
2724		    }
2725		  ctx->saltlen = (unsigned int)strtoul (s, NULL, 10);
2726		  gcry_sexp_release (list);
2727		}
2728
2729              /* Get optional RANDOM-OVERRIDE.  */
2730              list = gcry_sexp_find_token (ldata, "random-override", 0);
2731              if (list)
2732                {
2733                  s = gcry_sexp_nth_data (list, 1, &n);
2734                  if (!s)
2735                    rc = GPG_ERR_NO_OBJ;
2736                  else if (n > 0)
2737                    {
2738                      random_override = gcry_malloc (n);
2739                      if (!random_override)
2740                        rc = gpg_err_code_from_syserror ();
2741                      else
2742                        {
2743                          memcpy (random_override, s, n);
2744                          random_override_len = n;
2745                        }
2746                    }
2747                  gcry_sexp_release (list);
2748                  if (rc)
2749                    goto leave;
2750                }
2751
2752              /* Encode the data.  (NBITS-1 is due to 8.1.1, step 1.) */
2753	      rc = pss_encode (ret_mpi, ctx->nbits - 1, ctx->hash_algo,
2754			       value, valuelen, ctx->saltlen,
2755                               random_override, random_override_len);
2756
2757              gcry_free (random_override);
2758	    }
2759        }
2760    }
2761  else if (ctx->encoding == PUBKEY_ENC_PSS && lhash
2762	   && ctx->op == PUBKEY_OP_VERIFY)
2763    {
2764      if (gcry_sexp_length (lhash) != 3)
2765        rc = GPG_ERR_INV_OBJ;
2766      else if ( !(s=gcry_sexp_nth_data (lhash, 1, &n)) || !n )
2767        rc = GPG_ERR_INV_OBJ;
2768      else
2769        {
2770	  ctx->hash_algo = get_hash_algo (s, n);
2771
2772          if (!ctx->hash_algo)
2773            rc = GPG_ERR_DIGEST_ALGO;
2774	  else
2775	    {
2776	      *ret_mpi = gcry_sexp_nth_mpi (lhash, 2, GCRYMPI_FMT_USG);
2777	      if (!*ret_mpi)
2778		rc = GPG_ERR_INV_OBJ;
2779	      ctx->verify_cmp = pss_verify_cmp;
2780	      ctx->verify_arg = *ret_mpi;
2781	    }
2782	}
2783    }
2784  else
2785    rc = GPG_ERR_CONFLICT;
2786
2787 leave:
2788  gcry_sexp_release (ldata);
2789  gcry_sexp_release (lhash);
2790  gcry_sexp_release (lvalue);
2791
2792  if (!rc)
2793    ctx->flags = parsed_flags;
2794  else
2795    {
2796      gcry_free (ctx->label);
2797      ctx->label = NULL;
2798    }
2799
2800  return rc;
2801}
2802
2803static void
2804init_encoding_ctx (struct pk_encoding_ctx *ctx, enum pk_operation op,
2805		   unsigned int nbits)
2806{
2807  ctx->op = op;
2808  ctx->nbits = nbits;
2809  ctx->encoding = PUBKEY_ENC_UNKNOWN;
2810  ctx->flags = 0;
2811  ctx->hash_algo = GCRY_MD_SHA1;
2812  ctx->label = NULL;
2813  ctx->labellen = 0;
2814  ctx->saltlen = 20;
2815  ctx->verify_cmp = NULL;
2816  ctx->verify_arg = NULL;
2817}
2818
2819
2820/*
2821   Do a PK encrypt operation
2822
2823   Caller has to provide a public key as the SEXP pkey and data as a
2824   SEXP with just one MPI in it. Alternatively S_DATA might be a
2825   complex S-Expression, similar to the one used for signature
2826   verification.  This provides a flag which allows to handle PKCS#1
2827   block type 2 padding.  The function returns a sexp which may be
2828   passed to to pk_decrypt.
2829
2830   Returns: 0 or an errorcode.
2831
2832   s_data = See comment for sexp_data_to_mpi
2833   s_pkey = <key-as-defined-in-sexp_to_key>
2834   r_ciph = (enc-val
2835               (<algo>
2836                 (<param_name1> <mpi>)
2837                 ...
2838                 (<param_namen> <mpi>)
2839               ))
2840
2841*/
2842gcry_error_t
2843gcry_pk_encrypt (gcry_sexp_t *r_ciph, gcry_sexp_t s_data, gcry_sexp_t s_pkey)
2844{
2845  gcry_mpi_t *pkey = NULL, data = NULL, *ciph = NULL;
2846  const char *algo_name, *algo_elems;
2847  struct pk_encoding_ctx ctx;
2848  gcry_err_code_t rc;
2849  gcry_pk_spec_t *pubkey = NULL;
2850  gcry_module_t module = NULL;
2851
2852  *r_ciph = NULL;
2853
2854  REGISTER_DEFAULT_PUBKEYS;
2855
2856  /* Get the key. */
2857  rc = sexp_to_key (s_pkey, 0, NULL, &pkey, &module);
2858  if (rc)
2859    goto leave;
2860
2861  gcry_assert (module);
2862  pubkey = (gcry_pk_spec_t *) module->spec;
2863
2864  /* If aliases for the algorithm name exists, take the first one
2865     instead of the regular name to adhere to SPKI conventions.  We
2866     assume that the first alias name is the lowercase version of the
2867     regular one.  This change is required for compatibility with
2868     1.1.12 generated S-expressions. */
2869  algo_name = pubkey->aliases? *pubkey->aliases : NULL;
2870  if (!algo_name || !*algo_name)
2871    algo_name = pubkey->name;
2872
2873  algo_elems = pubkey->elements_enc;
2874
2875  /* Get the stuff we want to encrypt. */
2876  init_encoding_ctx (&ctx, PUBKEY_OP_ENCRYPT, gcry_pk_get_nbits (s_pkey));
2877  rc = sexp_data_to_mpi (s_data, &data, &ctx);
2878  if (rc)
2879    goto leave;
2880
2881  /* Now we can encrypt DATA to CIPH. */
2882  ciph = gcry_calloc (strlen (algo_elems) + 1, sizeof (*ciph));
2883  if (!ciph)
2884    {
2885      rc = gpg_err_code_from_syserror ();
2886      goto leave;
2887    }
2888  rc = pubkey_encrypt (module->mod_id, ciph, data, pkey, ctx.flags);
2889  mpi_free (data);
2890  data = NULL;
2891  if (rc)
2892    goto leave;
2893
2894  /* We did it.  Now build the return list */
2895  if (ctx.encoding == PUBKEY_ENC_OAEP
2896      || ctx.encoding == PUBKEY_ENC_PKCS1)
2897    {
2898      /* We need to make sure to return the correct length to avoid
2899         problems with missing leading zeroes.  We know that this
2900         encoding does only make sense with RSA thus we don't need to
2901         build the S-expression on the fly.  */
2902      unsigned char *em;
2903      size_t emlen = (ctx.nbits+7)/8;
2904
2905      rc = octet_string_from_mpi (&em, NULL, ciph[0], emlen);
2906      if (rc)
2907        goto leave;
2908      rc = gcry_err_code (gcry_sexp_build (r_ciph, NULL,
2909                                           "(enc-val(%s(a%b)))",
2910                                           algo_name, (int)emlen, em));
2911      gcry_free (em);
2912      if (rc)
2913        goto leave;
2914    }
2915  else
2916    {
2917      char *string, *p;
2918      int i;
2919      size_t nelem = strlen (algo_elems);
2920      size_t needed = 19 + strlen (algo_name) + (nelem * 5);
2921      void **arg_list;
2922
2923      /* Build the string.  */
2924      string = p = gcry_malloc (needed);
2925      if (!string)
2926        {
2927          rc = gpg_err_code_from_syserror ();
2928          goto leave;
2929        }
2930      p = stpcpy ( p, "(enc-val(" );
2931      p = stpcpy ( p, algo_name );
2932      for (i=0; algo_elems[i]; i++ )
2933        {
2934          *p++ = '(';
2935          *p++ = algo_elems[i];
2936          p = stpcpy ( p, "%m)" );
2937        }
2938      strcpy ( p, "))" );
2939
2940      /* And now the ugly part: We don't have a function to pass an
2941       * array to a format string, so we have to do it this way :-(.  */
2942      /* FIXME: There is now such a format specifier, so we can
2943         change the code to be more clear. */
2944      arg_list = malloc (nelem * sizeof *arg_list);
2945      if (!arg_list)
2946        {
2947          rc = gpg_err_code_from_syserror ();
2948          goto leave;
2949        }
2950
2951      for (i = 0; i < nelem; i++)
2952        arg_list[i] = ciph + i;
2953
2954      rc = gcry_sexp_build_array (r_ciph, NULL, string, arg_list);
2955      free (arg_list);
2956      if (rc)
2957        BUG ();
2958      gcry_free (string);
2959    }
2960
2961 leave:
2962  if (pkey)
2963    {
2964      release_mpi_array (pkey);
2965      gcry_free (pkey);
2966    }
2967
2968  if (ciph)
2969    {
2970      release_mpi_array (ciph);
2971      gcry_free (ciph);
2972    }
2973
2974  if (module)
2975    {
2976      ath_mutex_lock (&pubkeys_registered_lock);
2977      _gcry_module_release (module);
2978      ath_mutex_unlock (&pubkeys_registered_lock);
2979    }
2980
2981  gcry_free (ctx.label);
2982
2983  return gcry_error (rc);
2984}
2985
2986/*
2987   Do a PK decrypt operation
2988
2989   Caller has to provide a secret key as the SEXP skey and data in a
2990   format as created by gcry_pk_encrypt.  For historic reasons the
2991   function returns simply an MPI as an S-expression part; this is
2992   deprecated and the new method should be used which returns a real
2993   S-expressionl this is selected by adding at least an empty flags
2994   list to S_DATA.
2995
2996   Returns: 0 or an errorcode.
2997
2998   s_data = (enc-val
2999              [(flags [raw, pkcs1, oaep])]
3000              (<algo>
3001                (<param_name1> <mpi>)
3002                ...
3003                (<param_namen> <mpi>)
3004              ))
3005   s_skey = <key-as-defined-in-sexp_to_key>
3006   r_plain= Either an incomplete S-expression without the parentheses
3007            or if the flags list is used (even if empty) a real S-expression:
3008            (value PLAIN).  In raw mode (or no flags given) the returned value
3009            is to be interpreted as a signed MPI, thus it may have an extra
3010            leading zero octet even if not included in the original data.
3011            With pkcs1 or oaep decoding enabled the returned value is a
3012            verbatim octet string.
3013 */
3014gcry_error_t
3015gcry_pk_decrypt (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t s_skey)
3016{
3017  gcry_mpi_t *skey = NULL, *data = NULL, plain = NULL;
3018  unsigned char *unpad = NULL;
3019  size_t unpadlen = 0;
3020  int modern, flags;
3021  struct pk_encoding_ctx ctx;
3022  gcry_err_code_t rc;
3023  gcry_module_t module_enc = NULL, module_key = NULL;
3024
3025  *r_plain = NULL;
3026  ctx.label = NULL;
3027
3028  REGISTER_DEFAULT_PUBKEYS;
3029
3030  rc = sexp_to_key (s_skey, 1, NULL, &skey, &module_key);
3031  if (rc)
3032    goto leave;
3033
3034  init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT, gcry_pk_get_nbits (s_skey));
3035  rc = sexp_to_enc (s_data, &data, &module_enc, &modern, &flags, &ctx);
3036  if (rc)
3037    goto leave;
3038
3039  if (module_key->mod_id != module_enc->mod_id)
3040    {
3041      rc = GPG_ERR_CONFLICT; /* Key algo does not match data algo. */
3042      goto leave;
3043    }
3044
3045  rc = pubkey_decrypt (module_key->mod_id, &plain, data, skey, flags);
3046  if (rc)
3047    goto leave;
3048
3049  /* Do un-padding if necessary. */
3050  switch (ctx.encoding)
3051    {
3052    case PUBKEY_ENC_PKCS1:
3053      rc = pkcs1_decode_for_encryption (&unpad, &unpadlen,
3054                                        gcry_pk_get_nbits (s_skey), plain);
3055      mpi_free (plain);
3056      plain = NULL;
3057      if (!rc)
3058        rc = gcry_err_code (gcry_sexp_build (r_plain, NULL, "(value %b)",
3059                                             (int)unpadlen, unpad));
3060      break;
3061
3062    case PUBKEY_ENC_OAEP:
3063      rc = oaep_decode (&unpad, &unpadlen,
3064                        gcry_pk_get_nbits (s_skey), ctx.hash_algo,
3065			plain, ctx.label, ctx.labellen);
3066      mpi_free (plain);
3067      plain = NULL;
3068      if (!rc)
3069        rc = gcry_err_code (gcry_sexp_build (r_plain, NULL, "(value %b)",
3070                                             (int)unpadlen, unpad));
3071      break;
3072
3073    default:
3074      /* Raw format.  For backward compatibility we need to assume a
3075         signed mpi by using the sexp format string "%m".  */
3076      rc = gcry_err_code (gcry_sexp_build
3077                          (r_plain, NULL, modern? "(value %m)" : "%m", plain));
3078      break;
3079    }
3080
3081 leave:
3082  gcry_free (unpad);
3083
3084  if (skey)
3085    {
3086      release_mpi_array (skey);
3087      gcry_free (skey);
3088    }
3089
3090  mpi_free (plain);
3091
3092  if (data)
3093    {
3094      release_mpi_array (data);
3095      gcry_free (data);
3096    }
3097
3098  if (module_key || module_enc)
3099    {
3100      ath_mutex_lock (&pubkeys_registered_lock);
3101      if (module_key)
3102	_gcry_module_release (module_key);
3103      if (module_enc)
3104	_gcry_module_release (module_enc);
3105      ath_mutex_unlock (&pubkeys_registered_lock);
3106    }
3107
3108  gcry_free (ctx.label);
3109
3110  return gcry_error (rc);
3111}
3112
3113
3114
3115/*
3116   Create a signature.
3117
3118   Caller has to provide a secret key as the SEXP skey and data
3119   expressed as a SEXP list hash with only one element which should
3120   instantly be available as a MPI. Alternatively the structure given
3121   below may be used for S_HASH, it provides the abiliy to pass flags
3122   to the operation; the flags defined by now are "pkcs1" which does
3123   PKCS#1 block type 1 style padding and "pss" for PSS encoding.
3124
3125   Returns: 0 or an errorcode.
3126            In case of 0 the function returns a new SEXP with the
3127            signature value; the structure of this signature depends on the
3128            other arguments but is always suitable to be passed to
3129            gcry_pk_verify
3130
3131   s_hash = See comment for sexp_data_to_mpi
3132
3133   s_skey = <key-as-defined-in-sexp_to_key>
3134   r_sig  = (sig-val
3135              (<algo>
3136                (<param_name1> <mpi>)
3137                ...
3138                (<param_namen> <mpi>))
3139             [(hash algo)])
3140
3141  Note that (hash algo) in R_SIG is not used.
3142*/
3143gcry_error_t
3144gcry_pk_sign (gcry_sexp_t *r_sig, gcry_sexp_t s_hash, gcry_sexp_t s_skey)
3145{
3146  gcry_mpi_t *skey = NULL, hash = NULL, *result = NULL;
3147  gcry_pk_spec_t *pubkey = NULL;
3148  gcry_module_t module = NULL;
3149  const char *algo_name, *algo_elems;
3150  struct pk_encoding_ctx ctx;
3151  int i;
3152  gcry_err_code_t rc;
3153
3154  *r_sig = NULL;
3155
3156  REGISTER_DEFAULT_PUBKEYS;
3157
3158  rc = sexp_to_key (s_skey, 1, NULL, &skey, &module);
3159  if (rc)
3160    goto leave;
3161
3162  gcry_assert (module);
3163  pubkey = (gcry_pk_spec_t *) module->spec;
3164  algo_name = pubkey->aliases? *pubkey->aliases : NULL;
3165  if (!algo_name || !*algo_name)
3166    algo_name = pubkey->name;
3167
3168  algo_elems = pubkey->elements_sig;
3169
3170  /* Get the stuff we want to sign.  Note that pk_get_nbits does also
3171      work on a private key. */
3172  init_encoding_ctx (&ctx, PUBKEY_OP_SIGN, gcry_pk_get_nbits (s_skey));
3173  rc = sexp_data_to_mpi (s_hash, &hash, &ctx);
3174  if (rc)
3175    goto leave;
3176
3177  result = gcry_calloc (strlen (algo_elems) + 1, sizeof (*result));
3178  if (!result)
3179    {
3180      rc = gpg_err_code_from_syserror ();
3181      goto leave;
3182    }
3183  rc = pubkey_sign (module->mod_id, result, hash, skey);
3184  if (rc)
3185    goto leave;
3186
3187  if (ctx.encoding == PUBKEY_ENC_PSS
3188      || ctx.encoding == PUBKEY_ENC_PKCS1)
3189    {
3190      /* We need to make sure to return the correct length to avoid
3191         problems with missing leading zeroes.  We know that this
3192         encoding does only make sense with RSA thus we don't need to
3193         build the S-expression on the fly.  */
3194      unsigned char *em;
3195      size_t emlen = (ctx.nbits+7)/8;
3196
3197      rc = octet_string_from_mpi (&em, NULL, result[0], emlen);
3198      if (rc)
3199        goto leave;
3200      rc = gcry_err_code (gcry_sexp_build (r_sig, NULL,
3201                                           "(sig-val(%s(s%b)))",
3202                                           algo_name, (int)emlen, em));
3203      gcry_free (em);
3204      if (rc)
3205        goto leave;
3206    }
3207  else
3208    {
3209      /* General purpose output encoding.  Do it on the fly.  */
3210      char *string, *p;
3211      size_t nelem, needed = strlen (algo_name) + 20;
3212      void **arg_list;
3213
3214      nelem = strlen (algo_elems);
3215
3216      /* Count elements, so that we can allocate enough space. */
3217      needed += 10 * nelem;
3218
3219      /* Build the string. */
3220      string = p = gcry_malloc (needed);
3221      if (!string)
3222        {
3223          rc = gpg_err_code_from_syserror ();
3224          goto leave;
3225        }
3226      p = stpcpy (p, "(sig-val(");
3227      p = stpcpy (p, algo_name);
3228      for (i = 0; algo_elems[i]; i++)
3229        {
3230          *p++ = '(';
3231          *p++ = algo_elems[i];
3232          p = stpcpy (p, "%M)");
3233        }
3234      strcpy (p, "))");
3235
3236      arg_list = malloc (nelem * sizeof *arg_list);
3237      if (!arg_list)
3238        {
3239          rc = gpg_err_code_from_syserror ();
3240          goto leave;
3241        }
3242
3243      for (i = 0; i < nelem; i++)
3244        arg_list[i] = result + i;
3245
3246      rc = gcry_sexp_build_array (r_sig, NULL, string, arg_list);
3247      free (arg_list);
3248      if (rc)
3249        BUG ();
3250      gcry_free (string);
3251    }
3252
3253 leave:
3254  if (skey)
3255    {
3256      release_mpi_array (skey);
3257      gcry_free (skey);
3258    }
3259
3260  if (hash)
3261    mpi_free (hash);
3262
3263  if (result)
3264    {
3265      release_mpi_array (result);
3266      gcry_free (result);
3267    }
3268
3269  return gcry_error (rc);
3270}
3271
3272
3273/*
3274   Verify a signature.
3275
3276   Caller has to supply the public key pkey, the signature sig and his
3277   hashvalue data.  Public key has to be a standard public key given
3278   as an S-Exp, sig is a S-Exp as returned from gcry_pk_sign and data
3279   must be an S-Exp like the one in sign too.  */
3280gcry_error_t
3281gcry_pk_verify (gcry_sexp_t s_sig, gcry_sexp_t s_hash, gcry_sexp_t s_pkey)
3282{
3283  gcry_module_t module_key = NULL, module_sig = NULL;
3284  gcry_mpi_t *pkey = NULL, hash = NULL, *sig = NULL;
3285  struct pk_encoding_ctx ctx;
3286  gcry_err_code_t rc;
3287
3288  REGISTER_DEFAULT_PUBKEYS;
3289
3290  rc = sexp_to_key (s_pkey, 0, NULL, &pkey, &module_key);
3291  if (rc)
3292    goto leave;
3293
3294  rc = sexp_to_sig (s_sig, &sig, &module_sig);
3295  if (rc)
3296    goto leave;
3297
3298  /* Fixme: Check that the algorithm of S_SIG is compatible to the one
3299     of S_PKEY.  */
3300
3301  if (module_key->mod_id != module_sig->mod_id)
3302    {
3303      rc = GPG_ERR_CONFLICT;
3304      goto leave;
3305    }
3306
3307  /* Get the stuff we want to verify. */
3308  init_encoding_ctx (&ctx, PUBKEY_OP_VERIFY, gcry_pk_get_nbits (s_pkey));
3309  rc = sexp_data_to_mpi (s_hash, &hash, &ctx);
3310  if (rc)
3311    goto leave;
3312
3313  rc = pubkey_verify (module_key->mod_id, hash, sig, pkey,
3314		      ctx.verify_cmp, &ctx);
3315
3316 leave:
3317  if (pkey)
3318    {
3319      release_mpi_array (pkey);
3320      gcry_free (pkey);
3321    }
3322  if (sig)
3323    {
3324      release_mpi_array (sig);
3325      gcry_free (sig);
3326    }
3327  if (hash)
3328    mpi_free (hash);
3329
3330  if (module_key || module_sig)
3331    {
3332      ath_mutex_lock (&pubkeys_registered_lock);
3333      if (module_key)
3334	_gcry_module_release (module_key);
3335      if (module_sig)
3336	_gcry_module_release (module_sig);
3337      ath_mutex_unlock (&pubkeys_registered_lock);
3338    }
3339
3340  return gcry_error (rc);
3341}
3342
3343
3344/*
3345   Test a key.
3346
3347   This may be used either for a public or a secret key to see whether
3348   the internal structure is okay.
3349
3350   Returns: 0 or an errorcode.
3351
3352   s_key = <key-as-defined-in-sexp_to_key> */
3353gcry_error_t
3354gcry_pk_testkey (gcry_sexp_t s_key)
3355{
3356  gcry_module_t module = NULL;
3357  gcry_mpi_t *key = NULL;
3358  gcry_err_code_t rc;
3359
3360  REGISTER_DEFAULT_PUBKEYS;
3361
3362  /* Note we currently support only secret key checking. */
3363  rc = sexp_to_key (s_key, 1, NULL, &key, &module);
3364  if (! rc)
3365    {
3366      rc = pubkey_check_secret_key (module->mod_id, key);
3367      release_mpi_array (key);
3368      gcry_free (key);
3369    }
3370  return gcry_error (rc);
3371}
3372
3373
3374/*
3375  Create a public key pair and return it in r_key.
3376  How the key is created depends on s_parms:
3377  (genkey
3378   (algo
3379     (parameter_name_1 ....)
3380      ....
3381     (parameter_name_n ....)
3382  ))
3383  The key is returned in a format depending on the
3384  algorithm. Both, private and secret keys are returned
3385  and optionally some additional informatin.
3386  For elgamal we return this structure:
3387  (key-data
3388   (public-key
3389     (elg
3390 	(p <mpi>)
3391 	(g <mpi>)
3392 	(y <mpi>)
3393     )
3394   )
3395   (private-key
3396     (elg
3397 	(p <mpi>)
3398 	(g <mpi>)
3399 	(y <mpi>)
3400 	(x <mpi>)
3401     )
3402   )
3403   (misc-key-info
3404      (pm1-factors n1 n2 ... nn)
3405   ))
3406 */
3407gcry_error_t
3408gcry_pk_genkey (gcry_sexp_t *r_key, gcry_sexp_t s_parms)
3409{
3410  gcry_pk_spec_t *pubkey = NULL;
3411  gcry_module_t module = NULL;
3412  gcry_sexp_t list = NULL;
3413  gcry_sexp_t l2 = NULL;
3414  gcry_sexp_t l3 = NULL;
3415  char *name = NULL;
3416  size_t n;
3417  gcry_err_code_t rc = GPG_ERR_NO_ERROR;
3418  int i, j;
3419  const char *algo_name = NULL;
3420  int algo;
3421  const char *sec_elems = NULL, *pub_elems = NULL;
3422  gcry_mpi_t skey[12];
3423  gcry_mpi_t *factors = NULL;
3424  gcry_sexp_t extrainfo = NULL;
3425  unsigned int nbits = 0;
3426  unsigned long use_e = 0;
3427
3428  skey[0] = NULL;
3429  *r_key = NULL;
3430
3431  REGISTER_DEFAULT_PUBKEYS;
3432
3433  list = gcry_sexp_find_token (s_parms, "genkey", 0);
3434  if (!list)
3435    {
3436      rc = GPG_ERR_INV_OBJ; /* Does not contain genkey data. */
3437      goto leave;
3438    }
3439
3440  l2 = gcry_sexp_cadr (list);
3441  gcry_sexp_release (list);
3442  list = l2;
3443  l2 = NULL;
3444  if (! list)
3445    {
3446      rc = GPG_ERR_NO_OBJ; /* No cdr for the genkey. */
3447      goto leave;
3448    }
3449
3450  name = _gcry_sexp_nth_string (list, 0);
3451  if (!name)
3452    {
3453      rc = GPG_ERR_INV_OBJ; /* Algo string missing.  */
3454      goto leave;
3455    }
3456
3457  ath_mutex_lock (&pubkeys_registered_lock);
3458  module = gcry_pk_lookup_name (name);
3459  ath_mutex_unlock (&pubkeys_registered_lock);
3460  gcry_free (name);
3461  name = NULL;
3462  if (!module)
3463    {
3464      rc = GPG_ERR_PUBKEY_ALGO; /* Unknown algorithm.  */
3465      goto leave;
3466    }
3467
3468  pubkey = (gcry_pk_spec_t *) module->spec;
3469  algo = module->mod_id;
3470  algo_name = pubkey->aliases? *pubkey->aliases : NULL;
3471  if (!algo_name || !*algo_name)
3472    algo_name = pubkey->name;
3473  pub_elems = pubkey->elements_pkey;
3474  sec_elems = pubkey->elements_skey;
3475  if (strlen (sec_elems) >= DIM(skey))
3476    BUG ();
3477
3478  /* Handle the optional rsa-use-e element.  Actually this belong into
3479     the algorithm module but we have this parameter in the public
3480     module API, so we need to parse it right here.  */
3481  l2 = gcry_sexp_find_token (list, "rsa-use-e", 0);
3482  if (l2)
3483    {
3484      char buf[50];
3485      const char *s;
3486
3487      s = gcry_sexp_nth_data (l2, 1, &n);
3488      if ( !s || n >= DIM (buf) - 1 )
3489        {
3490          rc = GPG_ERR_INV_OBJ; /* No value or value too large.  */
3491          goto leave;
3492        }
3493      memcpy (buf, s, n);
3494      buf[n] = 0;
3495      use_e = strtoul (buf, NULL, 0);
3496      gcry_sexp_release (l2);
3497      l2 = NULL;
3498    }
3499  else
3500    use_e = 65537; /* Not given, use the value generated by old versions. */
3501
3502
3503  /* Get the "nbits" parameter.  */
3504  l2 = gcry_sexp_find_token (list, "nbits", 0);
3505  if (l2)
3506    {
3507      char buf[50];
3508      const char *s;
3509
3510      s = gcry_sexp_nth_data (l2, 1, &n);
3511      if (!s || n >= DIM (buf) - 1 )
3512        {
3513          rc = GPG_ERR_INV_OBJ; /* NBITS given without a cdr.  */
3514          goto leave;
3515        }
3516      memcpy (buf, s, n);
3517      buf[n] = 0;
3518      nbits = (unsigned int)strtoul (buf, NULL, 0);
3519      gcry_sexp_release (l2); l2 = NULL;
3520    }
3521  else
3522    nbits = 0;
3523
3524  /* Pass control to the algorithm module. */
3525  rc = pubkey_generate (module->mod_id, nbits, use_e, list, skey,
3526                        &factors, &extrainfo);
3527  gcry_sexp_release (list); list = NULL;
3528  if (rc)
3529    goto leave;
3530
3531  /* Key generation succeeded: Build an S-expression.  */
3532  {
3533    char *string, *p;
3534    size_t nelem=0, nelem_cp = 0, needed=0;
3535    gcry_mpi_t mpis[30];
3536    int percent_s_idx = -1;
3537
3538    /* Estimate size of format string.  */
3539    nelem = strlen (pub_elems) + strlen (sec_elems);
3540    if (factors)
3541      {
3542        for (i = 0; factors[i]; i++)
3543          nelem++;
3544      }
3545    nelem_cp = nelem;
3546
3547    needed += nelem * 10;
3548    /* (+5 is for EXTRAINFO ("%S")).  */
3549    needed += 2 * strlen (algo_name) + 300 + 5;
3550    if (nelem > DIM (mpis))
3551      BUG ();
3552
3553    /* Build the string. */
3554    nelem = 0;
3555    string = p = gcry_malloc (needed);
3556    if (!string)
3557      {
3558        rc = gpg_err_code_from_syserror ();
3559        goto leave;
3560      }
3561    p = stpcpy (p, "(key-data");
3562    p = stpcpy (p, "(public-key(");
3563    p = stpcpy (p, algo_name);
3564    for(i = 0; pub_elems[i]; i++)
3565      {
3566        *p++ = '(';
3567        *p++ = pub_elems[i];
3568        p = stpcpy (p, "%m)");
3569        mpis[nelem++] = skey[i];
3570      }
3571    if (extrainfo && (algo == GCRY_PK_ECDSA || algo == GCRY_PK_ECDH))
3572      {
3573        /* Very ugly hack to insert the used curve parameter into the
3574           list of public key parameters.  */
3575        percent_s_idx = nelem;
3576        p = stpcpy (p, "%S");
3577      }
3578    p = stpcpy (p, "))");
3579    p = stpcpy (p, "(private-key(");
3580    p = stpcpy (p, algo_name);
3581    for (i = 0; sec_elems[i]; i++)
3582      {
3583        *p++ = '(';
3584        *p++ = sec_elems[i];
3585        p = stpcpy (p, "%m)");
3586        mpis[nelem++] = skey[i];
3587      }
3588    p = stpcpy (p, "))");
3589
3590    /* Hack to make release_mpi_array() work.  */
3591    skey[i] = NULL;
3592
3593    if (extrainfo && percent_s_idx == -1)
3594      {
3595        /* If we have extrainfo we should not have any factors.  */
3596        p = stpcpy (p, "%S");
3597      }
3598    else if (factors && factors[0])
3599      {
3600        p = stpcpy (p, "(misc-key-info(pm1-factors");
3601        for(i = 0; factors[i]; i++)
3602          {
3603            p = stpcpy (p, "%m");
3604            mpis[nelem++] = factors[i];
3605          }
3606        p = stpcpy (p, "))");
3607      }
3608    strcpy (p, ")");
3609    gcry_assert (p - string < needed);
3610
3611    while (nelem < DIM (mpis))
3612      mpis[nelem++] = NULL;
3613
3614    {
3615      int elem_n = strlen (pub_elems) + strlen (sec_elems);
3616      void **arg_list;
3617
3618      /* Allocate one extra for EXTRAINFO ("%S").  */
3619      arg_list = gcry_calloc (nelem_cp+1, sizeof *arg_list);
3620      if (!arg_list)
3621        {
3622          rc = gpg_err_code_from_syserror ();
3623          goto leave;
3624        }
3625      for (i = j = 0; i < elem_n; i++)
3626        {
3627          if (i == percent_s_idx)
3628            arg_list[j++] = &extrainfo;
3629          arg_list[j++] = mpis + i;
3630        }
3631      if (extrainfo && percent_s_idx == -1)
3632        arg_list[j] = &extrainfo;
3633      else if (factors && factors[0])
3634        {
3635          for (; i < nelem_cp; i++)
3636            arg_list[j++] = factors + i - elem_n;
3637        }
3638      rc = gcry_sexp_build_array (r_key, NULL, string, arg_list);
3639      gcry_free (arg_list);
3640      if (rc)
3641	BUG ();
3642      gcry_assert (DIM (mpis) == 30); /* Reminder to make sure that
3643                                         the array gets increased if
3644                                         new parameters are added. */
3645    }
3646    gcry_free (string);
3647  }
3648
3649 leave:
3650  gcry_free (name);
3651  gcry_sexp_release (extrainfo);
3652  release_mpi_array (skey);
3653  /* Don't free SKEY itself, it is an stack allocated array. */
3654
3655  if (factors)
3656    {
3657      release_mpi_array ( factors );
3658      gcry_free (factors);
3659    }
3660
3661  gcry_sexp_release (l3);
3662  gcry_sexp_release (l2);
3663  gcry_sexp_release (list);
3664
3665  if (module)
3666    {
3667      ath_mutex_lock (&pubkeys_registered_lock);
3668      _gcry_module_release (module);
3669      ath_mutex_unlock (&pubkeys_registered_lock);
3670    }
3671
3672  return gcry_error (rc);
3673}
3674
3675
3676/*
3677   Get the number of nbits from the public key.
3678
3679   Hmmm: Should we have really this function or is it better to have a
3680   more general function to retrieve different properties of the key?  */
3681unsigned int
3682gcry_pk_get_nbits (gcry_sexp_t key)
3683{
3684  gcry_module_t module = NULL;
3685  gcry_pk_spec_t *pubkey;
3686  gcry_mpi_t *keyarr = NULL;
3687  unsigned int nbits = 0;
3688  gcry_err_code_t rc;
3689
3690  REGISTER_DEFAULT_PUBKEYS;
3691
3692  rc = sexp_to_key (key, 0, NULL, &keyarr, &module);
3693  if (rc == GPG_ERR_INV_OBJ)
3694    rc = sexp_to_key (key, 1, NULL, &keyarr, &module);
3695  if (rc)
3696    return 0; /* Error - 0 is a suitable indication for that. */
3697
3698  pubkey = (gcry_pk_spec_t *) module->spec;
3699  nbits = (*pubkey->get_nbits) (module->mod_id, keyarr);
3700
3701  ath_mutex_lock (&pubkeys_registered_lock);
3702  _gcry_module_release (module);
3703  ath_mutex_unlock (&pubkeys_registered_lock);
3704
3705  release_mpi_array (keyarr);
3706  gcry_free (keyarr);
3707
3708  return nbits;
3709}
3710
3711
3712/* Return the so called KEYGRIP which is the SHA-1 hash of the public
3713   key parameters expressed in a way depending on the algorithm.
3714
3715   ARRAY must either be 20 bytes long or NULL; in the latter case a
3716   newly allocated array of that size is returned, otherwise ARRAY or
3717   NULL is returned to indicate an error which is most likely an
3718   unknown algorithm.  The function accepts public or secret keys. */
3719unsigned char *
3720gcry_pk_get_keygrip (gcry_sexp_t key, unsigned char *array)
3721{
3722  gcry_sexp_t list = NULL, l2 = NULL;
3723  gcry_pk_spec_t *pubkey = NULL;
3724  gcry_module_t module = NULL;
3725  pk_extra_spec_t *extraspec;
3726  const char *s;
3727  char *name = NULL;
3728  int idx;
3729  const char *elems;
3730  gcry_md_hd_t md = NULL;
3731  int okay = 0;
3732
3733  REGISTER_DEFAULT_PUBKEYS;
3734
3735  /* Check that the first element is valid. */
3736  list = gcry_sexp_find_token (key, "public-key", 0);
3737  if (! list)
3738    list = gcry_sexp_find_token (key, "private-key", 0);
3739  if (! list)
3740    list = gcry_sexp_find_token (key, "protected-private-key", 0);
3741  if (! list)
3742    list = gcry_sexp_find_token (key, "shadowed-private-key", 0);
3743  if (! list)
3744    return NULL; /* No public- or private-key object. */
3745
3746  l2 = gcry_sexp_cadr (list);
3747  gcry_sexp_release (list);
3748  list = l2;
3749  l2 = NULL;
3750
3751  name = _gcry_sexp_nth_string (list, 0);
3752  if (!name)
3753    goto fail; /* Invalid structure of object. */
3754
3755  ath_mutex_lock (&pubkeys_registered_lock);
3756  module = gcry_pk_lookup_name (name);
3757  ath_mutex_unlock (&pubkeys_registered_lock);
3758
3759  if (!module)
3760    goto fail; /* Unknown algorithm.  */
3761
3762  pubkey = (gcry_pk_spec_t *) module->spec;
3763  extraspec = module->extraspec;
3764
3765  elems = pubkey->elements_grip;
3766  if (!elems)
3767    goto fail; /* No grip parameter.  */
3768
3769  if (gcry_md_open (&md, GCRY_MD_SHA1, 0))
3770    goto fail;
3771
3772  if (extraspec && extraspec->comp_keygrip)
3773    {
3774      /* Module specific method to compute a keygrip.  */
3775      if (extraspec->comp_keygrip (md, list))
3776        goto fail;
3777    }
3778  else
3779    {
3780      /* Generic method to compute a keygrip.  */
3781      for (idx = 0, s = elems; *s; s++, idx++)
3782        {
3783          const char *data;
3784          size_t datalen;
3785          char buf[30];
3786
3787          l2 = gcry_sexp_find_token (list, s, 1);
3788          if (! l2)
3789            goto fail;
3790          data = gcry_sexp_nth_data (l2, 1, &datalen);
3791          if (! data)
3792            goto fail;
3793
3794          snprintf (buf, sizeof buf, "(1:%c%u:", *s, (unsigned int)datalen);
3795          gcry_md_write (md, buf, strlen (buf));
3796          gcry_md_write (md, data, datalen);
3797          gcry_sexp_release (l2);
3798          l2 = NULL;
3799          gcry_md_write (md, ")", 1);
3800        }
3801    }
3802
3803  if (!array)
3804    {
3805      array = gcry_malloc (20);
3806      if (! array)
3807        goto fail;
3808    }
3809
3810  memcpy (array, gcry_md_read (md, GCRY_MD_SHA1), 20);
3811  okay = 1;
3812
3813 fail:
3814  gcry_free (name);
3815  gcry_sexp_release (l2);
3816  gcry_md_close (md);
3817  gcry_sexp_release (list);
3818  return okay? array : NULL;
3819}
3820
3821
3822
3823const char *
3824gcry_pk_get_curve (gcry_sexp_t key, int iterator, unsigned int *r_nbits)
3825{
3826  gcry_mpi_t *pkey = NULL;
3827  gcry_sexp_t list = NULL;
3828  gcry_sexp_t l2;
3829  gcry_module_t module = NULL;
3830  pk_extra_spec_t *extraspec;
3831  char *name = NULL;
3832  const char *result = NULL;
3833  int want_private = 1;
3834
3835  if (r_nbits)
3836    *r_nbits = 0;
3837
3838  REGISTER_DEFAULT_PUBKEYS;
3839
3840  if (key)
3841    {
3842      iterator = 0;
3843
3844      /* Check that the first element is valid. */
3845      list = gcry_sexp_find_token (key, "public-key", 0);
3846      if (list)
3847        want_private = 0;
3848      if (!list)
3849        list = gcry_sexp_find_token (key, "private-key", 0);
3850      if (!list)
3851        return NULL; /* No public- or private-key object. */
3852
3853      l2 = gcry_sexp_cadr (list);
3854      gcry_sexp_release (list);
3855      list = l2;
3856      l2 = NULL;
3857
3858      name = _gcry_sexp_nth_string (list, 0);
3859      if (!name)
3860        goto leave; /* Invalid structure of object. */
3861
3862      /* Get the key.  We pass the names of the parameters for
3863         override_elems; this allows to call this function without the
3864         actual public key parameter.  */
3865      if (sexp_to_key (key, want_private, "pabgn", &pkey, &module))
3866        goto leave;
3867    }
3868  else
3869    {
3870      ath_mutex_lock (&pubkeys_registered_lock);
3871      module = gcry_pk_lookup_name ("ecc");
3872      ath_mutex_unlock (&pubkeys_registered_lock);
3873      if (!module)
3874        goto leave;
3875    }
3876
3877  extraspec = module->extraspec;
3878  if (!extraspec || !extraspec->get_curve)
3879    goto leave;
3880
3881  result = extraspec->get_curve (pkey, iterator, r_nbits);
3882
3883 leave:
3884  if (pkey)
3885    {
3886      release_mpi_array (pkey);
3887      gcry_free (pkey);
3888    }
3889  if (module)
3890    {
3891      ath_mutex_lock (&pubkeys_registered_lock);
3892      _gcry_module_release (module);
3893      ath_mutex_unlock (&pubkeys_registered_lock);
3894    }
3895  gcry_free (name);
3896  gcry_sexp_release (list);
3897  return result;
3898}
3899
3900
3901
3902gcry_sexp_t
3903gcry_pk_get_param (int algo, const char *name)
3904{
3905  gcry_module_t module = NULL;
3906  pk_extra_spec_t *extraspec;
3907  gcry_sexp_t result = NULL;
3908
3909  if (algo != GCRY_PK_ECDSA && algo != GCRY_PK_ECDH)
3910    return NULL;
3911
3912  REGISTER_DEFAULT_PUBKEYS;
3913
3914  ath_mutex_lock (&pubkeys_registered_lock);
3915  module = gcry_pk_lookup_name ("ecc");
3916  ath_mutex_unlock (&pubkeys_registered_lock);
3917  if (module)
3918    {
3919      extraspec = module->extraspec;
3920      if (extraspec && extraspec->get_curve_param)
3921        result = extraspec->get_curve_param (name);
3922
3923      ath_mutex_lock (&pubkeys_registered_lock);
3924      _gcry_module_release (module);
3925      ath_mutex_unlock (&pubkeys_registered_lock);
3926    }
3927  return result;
3928}
3929
3930
3931
3932gcry_error_t
3933gcry_pk_ctl (int cmd, void *buffer, size_t buflen)
3934{
3935  gcry_err_code_t err = GPG_ERR_NO_ERROR;
3936
3937  REGISTER_DEFAULT_PUBKEYS;
3938
3939  switch (cmd)
3940    {
3941    case GCRYCTL_DISABLE_ALGO:
3942      /* This one expects a buffer pointing to an integer with the
3943         algo number.  */
3944      if ((! buffer) || (buflen != sizeof (int)))
3945	err = GPG_ERR_INV_ARG;
3946      else
3947	disable_pubkey_algo (*((int *) buffer));
3948      break;
3949
3950    default:
3951      err = GPG_ERR_INV_OP;
3952    }
3953
3954  return gcry_error (err);
3955}
3956
3957
3958/* Return information about the given algorithm
3959
3960   WHAT selects the kind of information returned:
3961
3962    GCRYCTL_TEST_ALGO:
3963        Returns 0 when the specified algorithm is available for use.
3964        Buffer must be NULL, nbytes  may have the address of a variable
3965        with the required usage of the algorithm. It may be 0 for don't
3966        care or a combination of the GCRY_PK_USAGE_xxx flags;
3967
3968    GCRYCTL_GET_ALGO_USAGE:
3969        Return the usage flags for the given algo.  An invalid algo
3970        returns 0.  Disabled algos are ignored here because we
3971        only want to know whether the algo is at all capable of
3972        the usage.
3973
3974   Note: Because this function is in most cases used to return an
3975   integer value, we can make it easier for the caller to just look at
3976   the return value.  The caller will in all cases consult the value
3977   and thereby detecting whether a error occurred or not (i.e. while
3978   checking the block size) */
3979gcry_error_t
3980gcry_pk_algo_info (int algorithm, int what, void *buffer, size_t *nbytes)
3981{
3982  gcry_err_code_t err = GPG_ERR_NO_ERROR;
3983
3984  switch (what)
3985    {
3986    case GCRYCTL_TEST_ALGO:
3987      {
3988	int use = nbytes ? *nbytes : 0;
3989	if (buffer)
3990	  err = GPG_ERR_INV_ARG;
3991	else if (check_pubkey_algo (algorithm, use))
3992	  err = GPG_ERR_PUBKEY_ALGO;
3993	break;
3994      }
3995
3996    case GCRYCTL_GET_ALGO_USAGE:
3997      {
3998	gcry_module_t pubkey;
3999	int use = 0;
4000
4001	REGISTER_DEFAULT_PUBKEYS;
4002
4003	ath_mutex_lock (&pubkeys_registered_lock);
4004	pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
4005	if (pubkey)
4006	  {
4007	    use = ((gcry_pk_spec_t *) pubkey->spec)->use;
4008	    _gcry_module_release (pubkey);
4009	  }
4010	ath_mutex_unlock (&pubkeys_registered_lock);
4011
4012	/* FIXME? */
4013	*nbytes = use;
4014
4015	break;
4016      }
4017
4018    case GCRYCTL_GET_ALGO_NPKEY:
4019      {
4020	/* FIXME?  */
4021	int npkey = pubkey_get_npkey (algorithm);
4022	*nbytes = npkey;
4023	break;
4024      }
4025    case GCRYCTL_GET_ALGO_NSKEY:
4026      {
4027	/* FIXME?  */
4028	int nskey = pubkey_get_nskey (algorithm);
4029	*nbytes = nskey;
4030	break;
4031      }
4032    case GCRYCTL_GET_ALGO_NSIGN:
4033      {
4034	/* FIXME?  */
4035	int nsign = pubkey_get_nsig (algorithm);
4036	*nbytes = nsign;
4037	break;
4038      }
4039    case GCRYCTL_GET_ALGO_NENCR:
4040      {
4041	/* FIXME?  */
4042	int nencr = pubkey_get_nenc (algorithm);
4043	*nbytes = nencr;
4044	break;
4045      }
4046
4047    default:
4048      err = GPG_ERR_INV_OP;
4049    }
4050
4051  return gcry_error (err);
4052}
4053
4054
4055/* Explicitly initialize this module.  */
4056gcry_err_code_t
4057_gcry_pk_init (void)
4058{
4059  gcry_err_code_t err = GPG_ERR_NO_ERROR;
4060
4061  REGISTER_DEFAULT_PUBKEYS;
4062
4063  return err;
4064}
4065
4066
4067gcry_err_code_t
4068_gcry_pk_module_lookup (int algorithm, gcry_module_t *module)
4069{
4070  gcry_err_code_t err = GPG_ERR_NO_ERROR;
4071  gcry_module_t pubkey;
4072
4073  REGISTER_DEFAULT_PUBKEYS;
4074
4075  ath_mutex_lock (&pubkeys_registered_lock);
4076  pubkey = _gcry_module_lookup_id (pubkeys_registered, algorithm);
4077  if (pubkey)
4078    *module = pubkey;
4079  else
4080    err = GPG_ERR_PUBKEY_ALGO;
4081  ath_mutex_unlock (&pubkeys_registered_lock);
4082
4083  return err;
4084}
4085
4086
4087void
4088_gcry_pk_module_release (gcry_module_t module)
4089{
4090  ath_mutex_lock (&pubkeys_registered_lock);
4091  _gcry_module_release (module);
4092  ath_mutex_unlock (&pubkeys_registered_lock);
4093}
4094
4095/* Get a list consisting of the IDs of the loaded pubkey modules.  If
4096   LIST is zero, write the number of loaded pubkey modules to
4097   LIST_LENGTH and return.  If LIST is non-zero, the first
4098   *LIST_LENGTH algorithm IDs are stored in LIST, which must be of
4099   according size.  In case there are less pubkey modules than
4100   *LIST_LENGTH, *LIST_LENGTH is updated to the correct number.  */
4101gcry_error_t
4102gcry_pk_list (int *list, int *list_length)
4103{
4104  gcry_err_code_t err = GPG_ERR_NO_ERROR;
4105
4106  ath_mutex_lock (&pubkeys_registered_lock);
4107  err = _gcry_module_list (pubkeys_registered, list, list_length);
4108  ath_mutex_unlock (&pubkeys_registered_lock);
4109
4110  return err;
4111}
4112
4113
4114/* Run the selftests for pubkey algorithm ALGO with optional reporting
4115   function REPORT.  */
4116gpg_error_t
4117_gcry_pk_selftest (int algo, int extended, selftest_report_func_t report)
4118{
4119  gcry_module_t module = NULL;
4120  pk_extra_spec_t *extraspec = NULL;
4121  gcry_err_code_t ec = 0;
4122
4123  REGISTER_DEFAULT_PUBKEYS;
4124
4125  ath_mutex_lock (&pubkeys_registered_lock);
4126  module = _gcry_module_lookup_id (pubkeys_registered, algo);
4127  if (module && !(module->flags & FLAG_MODULE_DISABLED))
4128    extraspec = module->extraspec;
4129  ath_mutex_unlock (&pubkeys_registered_lock);
4130  if (extraspec && extraspec->selftest)
4131    ec = extraspec->selftest (algo, extended, report);
4132  else
4133    {
4134      ec = GPG_ERR_PUBKEY_ALGO;
4135      if (report)
4136        report ("pubkey", algo, "module",
4137                module && !(module->flags & FLAG_MODULE_DISABLED)?
4138                "no selftest available" :
4139                module? "algorithm disabled" : "algorithm not found");
4140    }
4141
4142  if (module)
4143    {
4144      ath_mutex_lock (&pubkeys_registered_lock);
4145      _gcry_module_release (module);
4146      ath_mutex_unlock (&pubkeys_registered_lock);
4147    }
4148  return gpg_error (ec);
4149}
4150
4151
4152/* This function is only used by ac.c!  */
4153gcry_err_code_t
4154_gcry_pk_get_elements (int algo, char **enc, char **sig)
4155{
4156  gcry_module_t pubkey;
4157  gcry_pk_spec_t *spec;
4158  gcry_err_code_t err;
4159  char *enc_cp;
4160  char *sig_cp;
4161
4162  REGISTER_DEFAULT_PUBKEYS;
4163
4164  enc_cp = NULL;
4165  sig_cp = NULL;
4166  spec = NULL;
4167
4168  pubkey = _gcry_module_lookup_id (pubkeys_registered, algo);
4169  if (! pubkey)
4170    {
4171      err = GPG_ERR_INTERNAL;
4172      goto out;
4173    }
4174  spec = pubkey->spec;
4175
4176  if (enc)
4177    {
4178      enc_cp = strdup (spec->elements_enc);
4179      if (! enc_cp)
4180	{
4181	  err = gpg_err_code_from_syserror ();
4182	  goto out;
4183	}
4184    }
4185
4186  if (sig)
4187    {
4188      sig_cp = strdup (spec->elements_sig);
4189      if (! sig_cp)
4190	{
4191	  err = gpg_err_code_from_syserror ();
4192	  goto out;
4193	}
4194    }
4195
4196  if (enc)
4197    *enc = enc_cp;
4198  if (sig)
4199    *sig = sig_cp;
4200  err = 0;
4201
4202 out:
4203
4204  _gcry_module_release (pubkey);
4205  if (err)
4206    {
4207      free (enc_cp);
4208      free (sig_cp);
4209    }
4210
4211  return err;
4212}
4213