1 /* keygen.c - Generate a key pair
2 * Copyright (C) 1998-2007, 2009-2011 Free Software Foundation, Inc.
3 * Copyright (C) 2014, 2015 Werner Koch
5 * This file is part of GnuPG.
7 * GnuPG is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * GnuPG 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 General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
28 #include <sys/types.h>
42 #include "keyserver-internal.h"
43 #include "call-agent.h"
45 #include "../common/shareddefs.h"
47 #include "mbox-util.h"
50 /* The default algorithms. If you change them remember to change them
51 also in gpg.c:gpgconf_list. You should also check that the value
52 is inside the bounds enforced by ask_keysize and gen_xxx. */
53 #define DEFAULT_STD_ALGO PUBKEY_ALGO_RSA
54 #define DEFAULT_STD_KEYSIZE 2048
55 #define DEFAULT_STD_CURVE NULL
56 #define DEFAULT_STD_SUBALGO PUBKEY_ALGO_RSA
57 #define DEFAULT_STD_SUBKEYSIZE 2048
58 #define DEFAULT_STD_SUBCURVE NULL
60 /* Flag bits used during key generation. */
61 #define KEYGEN_FLAG_NO_PROTECTION 1
62 #define KEYGEN_FLAG_TRANSIENT_KEY 2
64 /* Maximum number of supported algorithm preferences. */
84 pKEYCREATIONDATE, /* Same in seconds since epoch. */
86 pKEYEXPIRE, /* in n seconds */
87 pSUBKEYEXPIRE, /* in n seconds */
96 struct para_data_s *next;
103 struct revocation_key revkey;
108 struct output_control_s
112 unsigned int keygen_flags;
118 armor_filter_context_t *afx;
123 struct opaque_data_usage_and_pk {
129 static int prefs_initialized = 0;
130 static byte sym_prefs[MAX_PREFS];
131 static int nsym_prefs;
132 static byte hash_prefs[MAX_PREFS];
133 static int nhash_prefs;
134 static byte zip_prefs[MAX_PREFS];
135 static int nzip_prefs;
136 static int mdc_available,ks_modify;
138 static void do_generate_keypair( struct para_data_s *para,
139 struct output_control_s *outctrl, int card );
140 static int write_keyblock (iobuf_t out, kbnode_t node);
141 static gpg_error_t gen_card_key (int algo, int keyno, int is_primary,
143 u32 *timestamp, u32 expireval);
144 static int gen_card_key_with_backup (int algo, int keyno, int is_primary,
145 kbnode_t pub_root, u32 timestamp,
146 u32 expireval, struct para_data_s *para);
150 print_status_key_created (int letter, PKT_public_key *pk, const char *handle)
152 byte array[MAX_FINGERPRINT_LEN], *s;
159 buf = xmalloc (MAX_FINGERPRINT_LEN*2+31 + strlen (handle) + 1);
166 fingerprint_from_pk (pk, array, &n);
168 for (i=0; i < n ; i++, s++, p += 2)
169 sprintf (p, "%02X", *s);
174 for (i=0; handle[i] && i < 100; i++)
175 *p++ = isspace ((unsigned int)handle[i])? '_':handle[i];
178 write_status_text ((letter || pk)?STATUS_KEY_CREATED:STATUS_KEY_NOT_CREATED,
184 print_status_key_not_created (const char *handle)
186 print_status_key_created (0, NULL, handle);
192 write_uid( KBNODE root, const char *s )
194 PACKET *pkt = xmalloc_clear(sizeof *pkt );
195 size_t n = strlen(s);
197 pkt->pkttype = PKT_USER_ID;
198 pkt->pkt.user_id = xmalloc_clear( sizeof *pkt->pkt.user_id + n - 1 );
199 pkt->pkt.user_id->len = n;
200 pkt->pkt.user_id->ref = 1;
201 strcpy(pkt->pkt.user_id->name, s);
202 add_kbnode( root, new_kbnode( pkt ) );
206 do_add_key_flags (PKT_signature *sig, unsigned int use)
212 /* The spec says that all primary keys MUST be able to certify. */
213 if(sig->sig_class!=0x18)
216 if (use & PUBKEY_USAGE_SIG)
218 if (use & PUBKEY_USAGE_ENC)
219 buf[0] |= 0x04 | 0x08;
220 if (use & PUBKEY_USAGE_AUTH)
223 build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
228 keygen_add_key_expire (PKT_signature *sig, void *opaque)
230 PKT_public_key *pk = opaque;
236 if (pk->expiredate > pk->timestamp)
237 u = pk->expiredate - pk->timestamp;
241 buf[0] = (u >> 24) & 0xff;
242 buf[1] = (u >> 16) & 0xff;
243 buf[2] = (u >> 8) & 0xff;
245 build_sig_subpkt (sig, SIGSUBPKT_KEY_EXPIRE, buf, 4);
249 /* Make sure we don't leave a key expiration subpacket lying
251 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
259 keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
261 struct opaque_data_usage_and_pk *oduap = opaque;
263 do_add_key_flags (sig, oduap->usage);
264 return keygen_add_key_expire (sig, oduap->pk);
269 set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
273 for (i=0; i < *nbuf; i++ )
276 log_info (_("preference '%s' duplicated\n"), item);
280 if (*nbuf >= MAX_PREFS)
283 log_info(_("too many cipher preferences\n"));
285 log_info(_("too many digest preferences\n"));
287 log_info(_("too many compression preferences\n"));
294 buf[(*nbuf)++] = val;
299 * Parse the supplied string and use it to set the standard
300 * preferences. The string may be in a form like the one printed by
301 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
302 * cipher/hash/compress names. Use NULL to set the default
303 * preferences. Returns: 0 = okay
306 keygen_set_std_prefs (const char *string,int personal)
308 byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
309 int nsym=0, nhash=0, nzip=0, val, rc=0;
310 int mdc=1, modify=0; /* mdc defaults on, modify defaults off. */
311 char dummy_string[20*4+1]; /* Enough for 20 items. */
313 if (!string || !ascii_strcasecmp (string, "default"))
315 if (opt.def_preference_list)
316 string=opt.def_preference_list;
319 int any_compress = 0;
320 dummy_string[0]='\0';
322 /* The rationale why we use the order AES256,192,128 is
323 for compatibility reasons with PGP. If gpg would
324 define AES128 first, we would get the somewhat
327 gpg -r pgpkey -r gpgkey ---gives--> AES256
328 gpg -r gpgkey -r pgpkey ---gives--> AES
330 Note that by using --personal-cipher-preferences it is
331 possible to prefer AES128.
334 /* Make sure we do not add more than 15 items here, as we
335 could overflow the size of dummy_string. We currently
337 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES256) )
338 strcat(dummy_string,"S9 ");
339 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES192) )
340 strcat(dummy_string,"S8 ");
341 if ( !openpgp_cipher_test_algo (CIPHER_ALGO_AES) )
342 strcat(dummy_string,"S7 ");
343 strcat(dummy_string,"S2 "); /* 3DES */
345 /* The default hash algo order is:
346 SHA-256, SHA-384, SHA-512, SHA-224, SHA-1.
348 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA256))
349 strcat (dummy_string, "H8 ");
351 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA384))
352 strcat (dummy_string, "H9 ");
354 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA512))
355 strcat (dummy_string, "H10 ");
357 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA224))
358 strcat (dummy_string, "H11 ");
360 strcat (dummy_string, "H2 "); /* SHA-1 */
362 if(!check_compress_algo(COMPRESS_ALGO_ZLIB))
364 strcat(dummy_string,"Z2 ");
368 if(!check_compress_algo(COMPRESS_ALGO_BZIP2))
370 strcat(dummy_string,"Z3 ");
374 if(!check_compress_algo(COMPRESS_ALGO_ZIP))
376 strcat(dummy_string,"Z1 ");
380 /* In case we have no compress algo at all, declare that
381 we prefer no compresssion. */
383 strcat(dummy_string,"Z0 ");
385 /* Remove the trailing space. */
386 if (*dummy_string && dummy_string[strlen (dummy_string)-1] == ' ')
387 dummy_string[strlen (dummy_string)-1] = 0;
392 else if (!ascii_strcasecmp (string, "none"))
397 char *tok,*prefstring;
399 prefstring=xstrdup(string); /* need a writable string! */
401 while((tok=strsep(&prefstring," ,")))
403 if((val=string_to_cipher_algo (tok)))
405 if(set_one_pref(val,1,tok,sym,&nsym))
408 else if((val=string_to_digest_algo (tok)))
410 if(set_one_pref(val,2,tok,hash,&nhash))
413 else if((val=string_to_compress_algo(tok))>-1)
415 if(set_one_pref(val,3,tok,zip,&nzip))
418 else if (ascii_strcasecmp(tok,"mdc")==0)
420 else if (ascii_strcasecmp(tok,"no-mdc")==0)
422 else if (ascii_strcasecmp(tok,"ks-modify")==0)
424 else if (ascii_strcasecmp(tok,"no-ks-modify")==0)
428 log_info (_("invalid item '%s' in preference string\n"),tok);
440 if(personal==PREFTYPE_SYM)
442 xfree(opt.personal_cipher_prefs);
445 opt.personal_cipher_prefs=NULL;
450 opt.personal_cipher_prefs=
451 xmalloc(sizeof(prefitem_t *)*(nsym+1));
453 for (i=0; i<nsym; i++)
455 opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
456 opt.personal_cipher_prefs[i].value = sym[i];
459 opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
460 opt.personal_cipher_prefs[i].value = 0;
463 else if(personal==PREFTYPE_HASH)
465 xfree(opt.personal_digest_prefs);
468 opt.personal_digest_prefs=NULL;
473 opt.personal_digest_prefs=
474 xmalloc(sizeof(prefitem_t *)*(nhash+1));
476 for (i=0; i<nhash; i++)
478 opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
479 opt.personal_digest_prefs[i].value = hash[i];
482 opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
483 opt.personal_digest_prefs[i].value = 0;
486 else if(personal==PREFTYPE_ZIP)
488 xfree(opt.personal_compress_prefs);
491 opt.personal_compress_prefs=NULL;
496 opt.personal_compress_prefs=
497 xmalloc(sizeof(prefitem_t *)*(nzip+1));
499 for (i=0; i<nzip; i++)
501 opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
502 opt.personal_compress_prefs[i].value = zip[i];
505 opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
506 opt.personal_compress_prefs[i].value = 0;
512 memcpy (sym_prefs, sym, (nsym_prefs=nsym));
513 memcpy (hash_prefs, hash, (nhash_prefs=nhash));
514 memcpy (zip_prefs, zip, (nzip_prefs=nzip));
517 prefs_initialized = 1;
524 /* Return a fake user ID containing the preferences. Caller must
527 keygen_get_std_prefs(void)
530 PKT_user_id *uid=xmalloc_clear(sizeof(PKT_user_id));
532 if(!prefs_initialized)
533 keygen_set_std_prefs(NULL,0);
537 uid->prefs=xmalloc((sizeof(prefitem_t *)*
538 (nsym_prefs+nhash_prefs+nzip_prefs+1)));
540 for(i=0;i<nsym_prefs;i++,j++)
542 uid->prefs[j].type=PREFTYPE_SYM;
543 uid->prefs[j].value=sym_prefs[i];
546 for(i=0;i<nhash_prefs;i++,j++)
548 uid->prefs[j].type=PREFTYPE_HASH;
549 uid->prefs[j].value=hash_prefs[i];
552 for(i=0;i<nzip_prefs;i++,j++)
554 uid->prefs[j].type=PREFTYPE_ZIP;
555 uid->prefs[j].value=zip_prefs[i];
558 uid->prefs[j].type=PREFTYPE_NONE;
559 uid->prefs[j].value=0;
561 uid->flags.mdc=mdc_available;
562 uid->flags.ks_modify=ks_modify;
568 add_feature_mdc (PKT_signature *sig,int enabled)
575 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
576 /* Already set or cleared */
578 ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
581 if (!s || !n) { /* create a new one */
583 buf = xmalloc_clear (n);
591 buf[0] |= 0x01; /* MDC feature */
595 /* Are there any bits set? */
601 delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
603 build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
609 add_keyserver_modify (PKT_signature *sig,int enabled)
616 /* The keyserver modify flag is a negative flag (i.e. no-modify) */
619 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n );
620 /* Already set or cleared */
622 ((enabled && (s[0] & 0x80)) || (!enabled && !(s[0] & 0x80))))
625 if (!s || !n) { /* create a new one */
627 buf = xmalloc_clear (n);
635 buf[0] |= 0x80; /* no-modify flag */
639 /* Are there any bits set? */
645 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS);
647 build_sig_subpkt (sig, SIGSUBPKT_KS_FLAGS, buf, n);
654 keygen_upd_std_prefs (PKT_signature *sig, void *opaque)
658 if (!prefs_initialized)
659 keygen_set_std_prefs (NULL, 0);
662 build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
665 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
666 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
670 build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
673 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
674 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
678 build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
681 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
682 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
685 /* Make sure that the MDC feature flag is set if needed. */
686 add_feature_mdc (sig,mdc_available);
687 add_keyserver_modify (sig,ks_modify);
688 keygen_add_keyserver_url(sig,NULL);
695 * Add preference to the self signature packet.
696 * This is only called for packets with version > 3.
699 keygen_add_std_prefs (PKT_signature *sig, void *opaque)
701 PKT_public_key *pk = opaque;
703 do_add_key_flags (sig, pk->pubkey_usage);
704 keygen_add_key_expire (sig, opaque );
705 keygen_upd_std_prefs (sig, opaque);
706 keygen_add_keyserver_url (sig,NULL);
712 keygen_add_keyserver_url(PKT_signature *sig, void *opaque)
714 const char *url=opaque;
717 url=opt.def_keyserver_url;
720 build_sig_subpkt(sig,SIGSUBPKT_PREF_KS,url,strlen(url));
722 delete_sig_subpkt (sig->hashed,SIGSUBPKT_PREF_KS);
728 keygen_add_notations(PKT_signature *sig,void *opaque)
730 struct notation *notation;
732 /* We always start clean */
733 delete_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION);
734 delete_sig_subpkt(sig->unhashed,SIGSUBPKT_NOTATION);
735 sig->flags.notation=0;
737 for(notation=opaque;notation;notation=notation->next)
738 if(!notation->flags.ignore)
743 n1=strlen(notation->name);
744 if(notation->altvalue)
745 n2=strlen(notation->altvalue);
746 else if(notation->bdat)
749 n2=strlen(notation->value);
751 buf = xmalloc( 8 + n1 + n2 );
753 /* human readable or not */
754 buf[0] = notation->bdat?0:0x80;
755 buf[1] = buf[2] = buf[3] = 0;
760 memcpy(buf+8, notation->name, n1 );
761 if(notation->altvalue)
762 memcpy(buf+8+n1, notation->altvalue, n2 );
763 else if(notation->bdat)
764 memcpy(buf+8+n1, notation->bdat, n2 );
766 memcpy(buf+8+n1, notation->value, n2 );
767 build_sig_subpkt( sig, SIGSUBPKT_NOTATION |
768 (notation->flags.critical?SIGSUBPKT_FLAG_CRITICAL:0),
777 keygen_add_revkey (PKT_signature *sig, void *opaque)
779 struct revocation_key *revkey = opaque;
780 byte buf[2+MAX_FINGERPRINT_LEN];
782 buf[0] = revkey->class;
783 buf[1] = revkey->algid;
784 memcpy (&buf[2], revkey->fpr, MAX_FINGERPRINT_LEN);
786 build_sig_subpkt (sig, SIGSUBPKT_REV_KEY, buf, 2+MAX_FINGERPRINT_LEN);
788 /* All sigs with revocation keys set are nonrevocable. */
789 sig->flags.revocable = 0;
791 build_sig_subpkt (sig, SIGSUBPKT_REVOCABLE, buf, 1);
800 /* Create a back-signature. If TIMESTAMP is not NULL, use it for the
801 signature creation time. */
803 make_backsig (PKT_signature *sig, PKT_public_key *pk,
804 PKT_public_key *sub_pk, PKT_public_key *sub_psk,
805 u32 timestamp, const char *cache_nonce)
808 PKT_signature *backsig;
810 cache_public_key (sub_pk);
812 err = make_keysig_packet (&backsig, pk, NULL, sub_pk, sub_psk, 0x19,
813 0, timestamp, 0, NULL, NULL, cache_nonce);
815 log_error ("make_keysig_packet failed for backsig: %s\n",
819 /* Get it into a binary packed form. */
820 IOBUF backsig_out = iobuf_temp();
823 init_packet (&backsig_pkt);
824 backsig_pkt.pkttype = PKT_SIGNATURE;
825 backsig_pkt.pkt.signature = backsig;
826 err = build_packet (backsig_out, &backsig_pkt);
827 free_packet (&backsig_pkt);
829 log_error ("build_packet failed for backsig: %s\n", gpg_strerror (err));
833 byte *buf = iobuf_get_temp_buffer (backsig_out);
835 /* Remove the packet header. */
843 else if(buf[1] < 224)
845 pktlen = (buf[1]-192)*256;
846 pktlen += buf[2]+192;
849 else if (buf[1] == 255)
851 pktlen = buf32_to_size_t (buf+2);
868 pktlen = (size_t)buf[mark++] << 24;
869 pktlen |= buf[mark++] << 16;
872 pktlen |= buf[mark++] << 8;
875 pktlen |= buf[mark++];
881 /* Now make the binary blob into a subpacket. */
882 build_sig_subpkt (sig, SIGSUBPKT_SIGNATURE, buf, pktlen);
884 iobuf_close (backsig_out);
892 /* Write a direct key signature to the first key in ROOT using the key
893 PSK. REVKEY is describes the direct key signature and TIMESTAMP is
894 the timestamp to set on the signature. */
896 write_direct_sig (KBNODE root, PKT_public_key *psk,
897 struct revocation_key *revkey, u32 timestamp,
898 const char *cache_nonce)
907 log_info (_("writing direct signature\n"));
909 /* Get the pk packet from the pub_tree. */
910 node = find_kbnode (root, PKT_PUBLIC_KEY);
913 pk = node->pkt->pkt.public_key;
915 /* We have to cache the key, so that the verification of the
916 signature creation is able to retrieve the public key. */
917 cache_public_key (pk);
919 /* Make the signature. */
920 err = make_keysig_packet (&sig, pk, NULL,NULL, psk, 0x1F,
922 keygen_add_revkey, revkey, cache_nonce);
925 log_error ("make_keysig_packet failed: %s\n", gpg_strerror (err) );
929 pkt = xmalloc_clear (sizeof *pkt);
930 pkt->pkttype = PKT_SIGNATURE;
931 pkt->pkt.signature = sig;
932 add_kbnode (root, new_kbnode (pkt));
938 /* Write a self-signature to the first user id in ROOT using the key
939 PSK. USE and TIMESTAMP give the extra data we need for the
942 write_selfsigs (KBNODE root, PKT_public_key *psk,
943 unsigned int use, u32 timestamp, const char *cache_nonce)
953 log_info (_("writing self signature\n"));
955 /* Get the uid packet from the list. */
956 node = find_kbnode (root, PKT_USER_ID);
958 BUG(); /* No user id packet in tree. */
959 uid = node->pkt->pkt.user_id;
961 /* Get the pk packet from the pub_tree. */
962 node = find_kbnode (root, PKT_PUBLIC_KEY);
965 pk = node->pkt->pkt.public_key;
967 /* The usage has not yet been set - do it now. */
968 pk->pubkey_usage = use;
970 /* We have to cache the key, so that the verification of the
971 signature creation is able to retrieve the public key. */
972 cache_public_key (pk);
974 /* Make the signature. */
975 err = make_keysig_packet (&sig, pk, uid, NULL, psk, 0x13,
977 keygen_add_std_prefs, pk, cache_nonce);
980 log_error ("make_keysig_packet failed: %s\n", gpg_strerror (err));
984 pkt = xmalloc_clear (sizeof *pkt);
985 pkt->pkttype = PKT_SIGNATURE;
986 pkt->pkt.signature = sig;
987 add_kbnode (root, new_kbnode (pkt));
993 /* Write the key binding signature. If TIMESTAMP is not NULL use the
994 signature creation time. PRI_PSK is the key use for signing.
995 SUB_PSK is a key used to create a back-signature; that one is only
996 used if USE has the PUBKEY_USAGE_SIG capability. */
998 write_keybinding (KBNODE root, PKT_public_key *pri_psk, PKT_public_key *sub_psk,
999 unsigned int use, u32 timestamp, const char *cache_nonce)
1005 PKT_public_key *pri_pk, *sub_pk;
1006 struct opaque_data_usage_and_pk oduap;
1009 log_info(_("writing key binding signature\n"));
1011 /* Get the primary pk packet from the tree. */
1012 node = find_kbnode (root, PKT_PUBLIC_KEY);
1015 pri_pk = node->pkt->pkt.public_key;
1017 /* We have to cache the key, so that the verification of the
1018 * signature creation is able to retrieve the public key. */
1019 cache_public_key (pri_pk);
1021 /* Find the last subkey. */
1023 for (node = root; node; node = node->next )
1025 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
1026 sub_pk = node->pkt->pkt.public_key;
1031 /* Make the signature. */
1034 err = make_keysig_packet (&sig, pri_pk, NULL, sub_pk, pri_psk, 0x18,
1036 keygen_add_key_flags_and_expire, &oduap,
1040 log_error ("make_keysig_packeto failed: %s\n", gpg_strerror (err));
1044 /* Make a backsig. */
1045 if (use & PUBKEY_USAGE_SIG)
1047 err = make_backsig (sig, pri_pk, sub_pk, sub_psk, timestamp, cache_nonce);
1052 pkt = xmalloc_clear ( sizeof *pkt );
1053 pkt->pkttype = PKT_SIGNATURE;
1054 pkt->pkt.signature = sig;
1055 add_kbnode (root, new_kbnode (pkt) );
1061 ecckey_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp, int algo)
1064 gcry_sexp_t list, l2;
1074 list = gcry_sexp_find_token (sexp, "public-key", 0);
1076 return gpg_error (GPG_ERR_INV_OBJ);
1077 l2 = gcry_sexp_cadr (list);
1078 gcry_sexp_release (list);
1081 return gpg_error (GPG_ERR_NO_OBJ);
1083 l2 = gcry_sexp_find_token (list, "curve", 0);
1086 err = gpg_error (GPG_ERR_NO_OBJ);
1089 curve = gcry_sexp_nth_string (l2, 1);
1092 err = gpg_error (GPG_ERR_NO_OBJ);
1095 gcry_sexp_release (l2);
1096 oidstr = openpgp_curve_to_oid (curve, &nbits);
1099 /* That can't happen because we used one of the curves
1100 gpg_curve_to_oid knows about. */
1101 err = gpg_error (GPG_ERR_INV_OBJ);
1104 err = openpgp_oid_from_str (oidstr, &array[0]);
1108 l2 = gcry_sexp_find_token (list, "q", 0);
1111 err = gpg_error (GPG_ERR_NO_OBJ);
1114 array[1] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1115 gcry_sexp_release (l2);
1118 err = gpg_error (GPG_ERR_INV_OBJ);
1121 gcry_sexp_release (list);
1123 if (algo == PUBKEY_ALGO_ECDH)
1125 array[2] = pk_ecdh_default_params (nbits);
1128 err = gpg_error_from_syserror ();
1136 for (i=0; i < 3; i++)
1138 gcry_mpi_release (array[i]);
1146 /* Extract key parameters from SEXP and store them in ARRAY. ELEMS is
1147 a string where each character denotes a parameter name. TOPNAME is
1148 the name of the top element above the elements. */
1150 key_from_sexp (gcry_mpi_t *array, gcry_sexp_t sexp,
1151 const char *topname, const char *elems)
1153 gcry_sexp_t list, l2;
1158 list = gcry_sexp_find_token (sexp, topname, 0);
1160 return gpg_error (GPG_ERR_INV_OBJ);
1161 l2 = gcry_sexp_cadr (list);
1162 gcry_sexp_release (list);
1165 return gpg_error (GPG_ERR_NO_OBJ);
1167 for (idx=0,s=elems; *s; s++, idx++)
1169 l2 = gcry_sexp_find_token (list, s, 1);
1172 rc = gpg_error (GPG_ERR_NO_OBJ); /* required parameter not found */
1175 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
1176 gcry_sexp_release (l2);
1179 rc = gpg_error (GPG_ERR_INV_OBJ); /* required parameter invalid */
1183 gcry_sexp_release (list);
1188 for (i=0; i<idx; i++)
1190 gcry_mpi_release (array[i]);
1193 gcry_sexp_release (list);
1199 /* Create a keyblock using the given KEYGRIP. ALGO is the OpenPGP
1200 algorithm of that keygrip. */
1202 do_create_from_keygrip (ctrl_t ctrl, int algo, const char *hexkeygrip,
1203 kbnode_t pub_root, u32 timestamp, u32 expireval,
1210 const char *algoelem;
1212 if (hexkeygrip[0] == '&')
1217 case PUBKEY_ALGO_RSA: algoelem = "ne"; break;
1218 case PUBKEY_ALGO_DSA: algoelem = "pqgy"; break;
1219 case PUBKEY_ALGO_ELGAMAL_E: algoelem = "pgy"; break;
1220 case PUBKEY_ALGO_ECDH:
1221 case PUBKEY_ALGO_ECDSA: algoelem = ""; break;
1222 case PUBKEY_ALGO_EDDSA: algoelem = ""; break;
1223 default: return gpg_error (GPG_ERR_INTERNAL);
1227 /* Ask the agent for the public key matching HEXKEYGRIP. */
1229 unsigned char *public;
1231 err = agent_readkey (ctrl, 0, hexkeygrip, &public);
1234 err = gcry_sexp_sscan (&s_key, NULL,
1235 public, gcry_sexp_canon_len (public, 0, NULL, NULL));
1241 /* Build a public key packet. */
1242 pk = xtrycalloc (1, sizeof *pk);
1245 err = gpg_error_from_syserror ();
1246 gcry_sexp_release (s_key);
1250 pk->timestamp = timestamp;
1253 pk->expiredate = pk->timestamp + expireval;
1254 pk->pubkey_algo = algo;
1256 if (algo == PUBKEY_ALGO_ECDSA
1257 || algo == PUBKEY_ALGO_EDDSA
1258 || algo == PUBKEY_ALGO_ECDH )
1259 err = ecckey_from_sexp (pk->pkey, s_key, algo);
1261 err = key_from_sexp (pk->pkey, s_key, "public-key", algoelem);
1264 log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
1265 gcry_sexp_release (s_key);
1266 free_public_key (pk);
1269 gcry_sexp_release (s_key);
1271 pkt = xtrycalloc (1, sizeof *pkt);
1274 err = gpg_error_from_syserror ();
1275 free_public_key (pk);
1279 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1280 pkt->pkt.public_key = pk;
1281 add_kbnode (pub_root, new_kbnode (pkt));
1287 /* Common code for the key generation fucntion gen_xxx. */
1289 common_gen (const char *keyparms, int algo, const char *algoelem,
1290 kbnode_t pub_root, u32 timestamp, u32 expireval, int is_subkey,
1291 int keygen_flags, const char *passphrase, char **cache_nonce_addr)
1298 err = agent_genkey (NULL, cache_nonce_addr, keyparms,
1299 !!(keygen_flags & KEYGEN_FLAG_NO_PROTECTION),
1304 log_error ("agent_genkey failed: %s\n", gpg_strerror (err) );
1308 pk = xtrycalloc (1, sizeof *pk);
1311 err = gpg_error_from_syserror ();
1312 gcry_sexp_release (s_key);
1316 pk->timestamp = timestamp;
1319 pk->expiredate = pk->timestamp + expireval;
1320 pk->pubkey_algo = algo;
1322 if (algo == PUBKEY_ALGO_ECDSA
1323 || algo == PUBKEY_ALGO_EDDSA
1324 || algo == PUBKEY_ALGO_ECDH )
1325 err = ecckey_from_sexp (pk->pkey, s_key, algo);
1327 err = key_from_sexp (pk->pkey, s_key, "public-key", algoelem);
1330 log_error ("key_from_sexp failed: %s\n", gpg_strerror (err) );
1331 gcry_sexp_release (s_key);
1332 free_public_key (pk);
1335 gcry_sexp_release (s_key);
1337 pkt = xtrycalloc (1, sizeof *pkt);
1340 err = gpg_error_from_syserror ();
1341 free_public_key (pk);
1345 pkt->pkttype = is_subkey ? PKT_PUBLIC_SUBKEY : PKT_PUBLIC_KEY;
1346 pkt->pkt.public_key = pk;
1347 add_kbnode (pub_root, new_kbnode (pkt));
1354 * Generate an Elgamal key.
1357 gen_elg (int algo, unsigned int nbits, KBNODE pub_root,
1358 u32 timestamp, u32 expireval, int is_subkey,
1359 int keygen_flags, const char *passphrase, char **cache_nonce_addr)
1365 assert (is_ELGAMAL (algo));
1370 log_info (_("keysize invalid; using %u bits\n"), nbits );
1372 else if (nbits > 4096)
1375 log_info (_("keysize invalid; using %u bits\n"), nbits );
1380 nbits = ((nbits + 31) / 32) * 32;
1381 log_info (_("keysize rounded up to %u bits\n"), nbits );
1384 /* Note that we use transient-key only if no-protection has also
1386 snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1387 keyparms = xtryasprintf ("(genkey(%s(nbits %zu:%s)%s))",
1388 algo == GCRY_PK_ELG_E ? "openpgp-elg" :
1389 algo == GCRY_PK_ELG ? "elg" : "x-oops" ,
1390 strlen (nbitsstr), nbitsstr,
1391 ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1392 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1393 "(transient-key)" : "" );
1395 err = gpg_error_from_syserror ();
1398 err = common_gen (keyparms, algo, "pgy",
1399 pub_root, timestamp, expireval, is_subkey,
1400 keygen_flags, passphrase, cache_nonce_addr);
1409 * Generate an DSA key
1412 gen_dsa (unsigned int nbits, KBNODE pub_root,
1413 u32 timestamp, u32 expireval, int is_subkey,
1414 int keygen_flags, const char *passphrase, char **cache_nonce_addr)
1425 log_info(_("keysize invalid; using %u bits\n"), nbits );
1427 else if ( nbits > 3072 )
1430 log_info(_("keysize invalid; using %u bits\n"), nbits );
1435 nbits = ((nbits + 63) / 64) * 64;
1436 log_info(_("keysize rounded up to %u bits\n"), nbits );
1439 /* To comply with FIPS rules we round up to the next value unless in
1441 if (!opt.expert && nbits > 1024 && (nbits % 1024))
1443 nbits = ((nbits + 1023) / 1024) * 1024;
1444 log_info(_("keysize rounded up to %u bits\n"), nbits );
1448 Figure out a q size based on the key size. FIPS 180-3 says:
1455 2048/256 is an odd pair since there is also a 2048/224 and
1456 3072/256. Matching sizes is not a very exact science.
1458 We'll do 256 qbits for nbits over 2047, 224 for nbits over 1024
1459 but less than 2048, and 160 for 1024 (DSA1).
1464 else if ( nbits > 1024)
1470 log_info (_("WARNING: some OpenPGP programs can't"
1471 " handle a DSA key with this digest size\n"));
1473 snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1474 snprintf (qbitsstr, sizeof qbitsstr, "%u", qbits);
1475 keyparms = xtryasprintf ("(genkey(dsa(nbits %zu:%s)(qbits %zu:%s)%s))",
1476 strlen (nbitsstr), nbitsstr,
1477 strlen (qbitsstr), qbitsstr,
1478 ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1479 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1480 "(transient-key)" : "" );
1482 err = gpg_error_from_syserror ();
1485 err = common_gen (keyparms, PUBKEY_ALGO_DSA, "pqgy",
1486 pub_root, timestamp, expireval, is_subkey,
1487 keygen_flags, passphrase, cache_nonce_addr);
1497 * Generate an ECC key
1500 gen_ecc (int algo, const char *curve, kbnode_t pub_root,
1501 u32 timestamp, u32 expireval, int is_subkey,
1502 int keygen_flags, const char *passphrase, char **cache_nonce_addr)
1507 assert (algo == PUBKEY_ALGO_ECDSA
1508 || algo == PUBKEY_ALGO_EDDSA
1509 || algo == PUBKEY_ALGO_ECDH);
1511 if (!curve || !*curve)
1512 return gpg_error (GPG_ERR_UNKNOWN_CURVE);
1514 /* Note that we use the "comp" flag with EdDSA to request the use of
1515 a 0x40 compression prefix octet. */
1516 if (algo == PUBKEY_ALGO_EDDSA)
1517 keyparms = xtryasprintf
1518 ("(genkey(ecc(curve %zu:%s)(flags eddsa comp%s)))",
1519 strlen (curve), curve,
1520 (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1521 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1522 " transient-key" : ""));
1523 else if (algo == PUBKEY_ALGO_ECDH && !strcmp (curve, "Curve25519"))
1524 keyparms = xtryasprintf
1525 ("(genkey(ecc(curve %zu:%s)(flags djb-tweak comp%s)))",
1526 strlen (curve), curve,
1527 (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1528 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1529 " transient-key" : ""));
1531 keyparms = xtryasprintf
1532 ("(genkey(ecc(curve %zu:%s)(flags nocomp%s)))",
1533 strlen (curve), curve,
1534 (((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1535 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1536 " transient-key" : ""));
1539 err = gpg_error_from_syserror ();
1542 err = common_gen (keyparms, algo, "",
1543 pub_root, timestamp, expireval, is_subkey,
1544 keygen_flags, passphrase, cache_nonce_addr);
1553 * Generate an RSA key.
1556 gen_rsa (int algo, unsigned int nbits, KBNODE pub_root,
1557 u32 timestamp, u32 expireval, int is_subkey,
1558 int keygen_flags, const char *passphrase, char **cache_nonce_addr)
1563 const unsigned maxsize = (opt.flags.large_rsa ? 8192 : 4096);
1565 assert (is_RSA(algo));
1568 nbits = DEFAULT_STD_KEYSIZE;
1573 log_info (_("keysize invalid; using %u bits\n"), nbits );
1575 else if (nbits > maxsize)
1578 log_info (_("keysize invalid; using %u bits\n"), nbits );
1583 nbits = ((nbits + 31) / 32) * 32;
1584 log_info (_("keysize rounded up to %u bits\n"), nbits );
1587 snprintf (nbitsstr, sizeof nbitsstr, "%u", nbits);
1588 keyparms = xtryasprintf ("(genkey(rsa(nbits %zu:%s)%s))",
1589 strlen (nbitsstr), nbitsstr,
1590 ((keygen_flags & KEYGEN_FLAG_TRANSIENT_KEY)
1591 && (keygen_flags & KEYGEN_FLAG_NO_PROTECTION))?
1592 "(transient-key)" : "" );
1594 err = gpg_error_from_syserror ();
1597 err = common_gen (keyparms, algo, "ne",
1598 pub_root, timestamp, expireval, is_subkey,
1599 keygen_flags, passphrase, cache_nonce_addr);
1609 * return 0 on error or the multiplier
1612 check_valid_days( const char *s )
1622 return 0; /* e.g. "2323wc" */
1623 if( *s == 'd' || *s == 'D' )
1625 if( *s == 'w' || *s == 'W' )
1627 if( *s == 'm' || *s == 'M' )
1629 if( *s == 'y' || *s == 'Y' )
1636 print_key_flags(int flags)
1638 if(flags&PUBKEY_USAGE_SIG)
1639 tty_printf("%s ",_("Sign"));
1641 if(flags&PUBKEY_USAGE_CERT)
1642 tty_printf("%s ",_("Certify"));
1644 if(flags&PUBKEY_USAGE_ENC)
1645 tty_printf("%s ",_("Encrypt"));
1647 if(flags&PUBKEY_USAGE_AUTH)
1648 tty_printf("%s ",_("Authenticate"));
1652 /* Returns the key flags */
1654 ask_key_flags(int algo,int subkey)
1656 /* TRANSLATORS: Please use only plain ASCII characters for the
1657 translation. If this is not possible use single digits. The
1658 string needs to 8 bytes long. Here is a description of the
1661 s = Toggle signing capability
1662 e = Toggle encryption capability
1663 a = Toggle authentication capability
1666 const char *togglers=_("SsEeAaQq");
1669 unsigned int current=0;
1670 unsigned int possible=openpgp_pk_algo_usage(algo);
1672 if ( strlen(togglers) != 8 )
1674 tty_printf ("NOTE: Bad translation at %s:%d. "
1675 "Please report.\n", __FILE__, __LINE__);
1676 togglers = "11223300";
1679 /* Only primary keys may certify. */
1681 possible&=~PUBKEY_USAGE_CERT;
1683 /* Preload the current set with the possible set, minus
1684 authentication, since nobody really uses auth yet. */
1685 current=possible&~PUBKEY_USAGE_AUTH;
1690 tty_printf(_("Possible actions for a %s key: "),
1691 openpgp_pk_algo_name (algo));
1692 print_key_flags(possible);
1694 tty_printf(_("Current allowed actions: "));
1695 print_key_flags(current);
1698 if(possible&PUBKEY_USAGE_SIG)
1699 tty_printf(_(" (%c) Toggle the sign capability\n"),
1701 if(possible&PUBKEY_USAGE_ENC)
1702 tty_printf(_(" (%c) Toggle the encrypt capability\n"),
1704 if(possible&PUBKEY_USAGE_AUTH)
1705 tty_printf(_(" (%c) Toggle the authenticate capability\n"),
1708 tty_printf(_(" (%c) Finished\n"),togglers[6]);
1712 answer = cpr_get("keygen.flags",_("Your selection? "));
1717 /* Hack to allow direct entry of the capabilities. */
1719 for (s=answer+1; *s; s++)
1721 if ((*s == 's' || *s == 'S') && (possible&PUBKEY_USAGE_SIG))
1722 current |= PUBKEY_USAGE_SIG;
1723 else if ((*s == 'e' || *s == 'E') && (possible&PUBKEY_USAGE_ENC))
1724 current |= PUBKEY_USAGE_ENC;
1725 else if ((*s == 'a' || *s == 'A') && (possible&PUBKEY_USAGE_AUTH))
1726 current |= PUBKEY_USAGE_AUTH;
1727 else if (!subkey && *s == 'c')
1729 /* Accept 'c' for the primary key because USAGE_CERT
1730 will will be set anyway. This is for folks who
1731 want to experiment with a cert-only primary key. */
1732 current |= PUBKEY_USAGE_CERT;
1737 else if (strlen(answer)>1)
1738 tty_printf(_("Invalid selection.\n"));
1739 else if(*answer=='\0' || *answer==togglers[6] || *answer==togglers[7])
1741 else if((*answer==togglers[0] || *answer==togglers[1])
1742 && possible&PUBKEY_USAGE_SIG)
1744 if(current&PUBKEY_USAGE_SIG)
1745 current&=~PUBKEY_USAGE_SIG;
1747 current|=PUBKEY_USAGE_SIG;
1749 else if((*answer==togglers[2] || *answer==togglers[3])
1750 && possible&PUBKEY_USAGE_ENC)
1752 if(current&PUBKEY_USAGE_ENC)
1753 current&=~PUBKEY_USAGE_ENC;
1755 current|=PUBKEY_USAGE_ENC;
1757 else if((*answer==togglers[4] || *answer==togglers[5])
1758 && possible&PUBKEY_USAGE_AUTH)
1760 if(current&PUBKEY_USAGE_AUTH)
1761 current&=~PUBKEY_USAGE_AUTH;
1763 current|=PUBKEY_USAGE_AUTH;
1766 tty_printf(_("Invalid selection.\n"));
1775 /* Check whether we have a key for the key with HEXGRIP. Returns 0 if
1776 there is no such key or the OpenPGP algo number for the key. */
1778 check_keygrip (ctrl_t ctrl, const char *hexgrip)
1781 unsigned char *public;
1783 const char *algostr;
1785 if (hexgrip[0] == '&')
1788 err = agent_readkey (ctrl, 0, hexgrip, &public);
1791 publiclen = gcry_sexp_canon_len (public, 0, NULL, NULL);
1793 get_pk_algo_from_canon_sexp (public, publiclen, &algostr);
1796 /* FIXME: Mapping of ECC algorithms is probably not correct. */
1799 else if (!strcmp (algostr, "rsa"))
1800 return PUBKEY_ALGO_RSA;
1801 else if (!strcmp (algostr, "dsa"))
1802 return PUBKEY_ALGO_DSA;
1803 else if (!strcmp (algostr, "elg"))
1804 return PUBKEY_ALGO_ELGAMAL_E;
1805 else if (!strcmp (algostr, "ecc"))
1806 return PUBKEY_ALGO_ECDH;
1807 else if (!strcmp (algostr, "ecdsa"))
1808 return PUBKEY_ALGO_ECDSA;
1809 else if (!strcmp (algostr, "eddsa"))
1810 return PUBKEY_ALGO_EDDSA;
1817 /* Ask for an algorithm. The function returns the algorithm id to
1818 * create. If ADDMODE is false the function won't show an option to
1819 * create the primary and subkey combined and won't set R_USAGE
1820 * either. If a combined algorithm has been selected, the subkey
1821 * algorithm is stored at R_SUBKEY_ALGO. If R_KEYGRIP is given, the
1822 * user has the choice to enter the keygrip of an existing key. That
1823 * keygrip is then stored at this address. The caller needs to free
1826 ask_algo (ctrl_t ctrl, int addmode, int *r_subkey_algo, unsigned int *r_usage,
1829 char *keygrip = NULL;
1830 char *answer = NULL;
1835 r_subkey_algo = &dummy_algo;
1837 tty_printf (_("Please select what kind of key you want:\n"));
1841 tty_printf (_(" (%d) RSA and RSA (default)\n"), 1 );
1845 tty_printf (_(" (%d) DSA and Elgamal\n"), 2 );
1847 tty_printf (_(" (%d) DSA (sign only)\n"), 3 );
1849 tty_printf (_(" (%d) RSA (sign only)\n"), 4 );
1854 tty_printf (_(" (%d) Elgamal (encrypt only)\n"), 5 );
1856 tty_printf (_(" (%d) RSA (encrypt only)\n"), 6 );
1861 tty_printf (_(" (%d) DSA (set your own capabilities)\n"), 7 );
1863 tty_printf (_(" (%d) RSA (set your own capabilities)\n"), 8 );
1867 #if GPG_USE_ECDSA || GPG_USE_ECDH || GPG_USE_EDDSA
1868 if (opt.expert && !addmode)
1869 tty_printf (_(" (%d) ECC and ECC\n"), 9 );
1871 tty_printf (_(" (%d) ECC (sign only)\n"), 10 );
1873 tty_printf (_(" (%d) ECC (set your own capabilities)\n"), 11 );
1874 if (opt.expert && addmode)
1875 tty_printf (_(" (%d) ECC (encrypt only)\n"), 12 );
1878 if (opt.expert && r_keygrip)
1879 tty_printf (_(" (%d) Existing key\n"), 13 );
1886 answer = cpr_get ("keygen.algo", _("Your selection? "));
1888 algo = *answer? atoi (answer) : 1;
1889 if ((algo == 1 || !strcmp (answer, "rsa+rsa")) && !addmode)
1891 algo = PUBKEY_ALGO_RSA;
1892 *r_subkey_algo = PUBKEY_ALGO_RSA;
1895 else if ((algo == 2 || !strcmp (answer, "dsa+elg")) && !addmode)
1897 algo = PUBKEY_ALGO_DSA;
1898 *r_subkey_algo = PUBKEY_ALGO_ELGAMAL_E;
1901 else if (algo == 3 || !strcmp (answer, "dsa"))
1903 algo = PUBKEY_ALGO_DSA;
1904 *r_usage = PUBKEY_USAGE_SIG;
1907 else if (algo == 4 || !strcmp (answer, "rsa/s"))
1909 algo = PUBKEY_ALGO_RSA;
1910 *r_usage = PUBKEY_USAGE_SIG;
1913 else if ((algo == 5 || !strcmp (answer, "elg")) && addmode)
1915 algo = PUBKEY_ALGO_ELGAMAL_E;
1916 *r_usage = PUBKEY_USAGE_ENC;
1919 else if ((algo == 6 || !strcmp (answer, "rsa/e")) && addmode)
1921 algo = PUBKEY_ALGO_RSA;
1922 *r_usage = PUBKEY_USAGE_ENC;
1925 else if ((algo == 7 || !strcmp (answer, "dsa/*")) && opt.expert)
1927 algo = PUBKEY_ALGO_DSA;
1928 *r_usage = ask_key_flags (algo, addmode);
1931 else if ((algo == 8 || !strcmp (answer, "rsa/*")) && opt.expert)
1933 algo = PUBKEY_ALGO_RSA;
1934 *r_usage = ask_key_flags (algo, addmode);
1937 else if ((algo == 9 || !strcmp (answer, "ecc+ecc"))
1938 && opt.expert && !addmode)
1940 algo = PUBKEY_ALGO_ECDSA;
1941 *r_subkey_algo = PUBKEY_ALGO_ECDH;
1944 else if ((algo == 10 || !strcmp (answer, "ecc/s")) && opt.expert)
1946 algo = PUBKEY_ALGO_ECDSA;
1947 *r_usage = PUBKEY_USAGE_SIG;
1950 else if ((algo == 11 || !strcmp (answer, "ecc/*")) && opt.expert)
1952 algo = PUBKEY_ALGO_ECDSA;
1953 *r_usage = ask_key_flags (algo, addmode);
1956 else if ((algo == 12 || !strcmp (answer, "ecc/e"))
1957 && opt.expert && addmode)
1959 algo = PUBKEY_ALGO_ECDH;
1960 *r_usage = PUBKEY_USAGE_ENC;
1963 else if ((algo == 13 || !strcmp (answer, "keygrip"))
1964 && opt.expert && r_keygrip)
1969 answer = tty_get (_("Enter the keygrip: "));
1971 trim_spaces (answer);
1979 if (strlen (answer) != 40 &&
1980 !(answer[0] == '&' && strlen (answer+1) == 40))
1982 (_("Not a valid keygrip (expecting 40 hex digits)\n"));
1983 else if (!(algo = check_keygrip (ctrl, answer)) )
1984 tty_printf (_("No key with this keygrip\n"));
1991 *r_usage = ask_key_flags (algo, addmode);
1995 tty_printf (_("Invalid selection.\n"));
2001 *r_keygrip = keygrip;
2006 /* Ask for the key size. ALGO is the algorithm. If PRIMARY_KEYSIZE
2007 is not 0, the function asks for the size of the encryption
2010 ask_keysize (int algo, unsigned int primary_keysize)
2012 unsigned int nbits, min, def = DEFAULT_STD_KEYSIZE, max=4096;
2013 int for_subkey = !!primary_keysize;
2021 if (primary_keysize && !opt.expert)
2023 /* Deduce the subkey size from the primary key size. */
2024 if (algo == PUBKEY_ALGO_DSA && primary_keysize > 3072)
2025 nbits = 3072; /* For performance reasons we don't support more
2026 than 3072 bit DSA. However we won't see this
2027 case anyway because DSA can't be used as an
2028 encryption subkey ;-). */
2030 nbits = primary_keysize;
2037 case PUBKEY_ALGO_DSA:
2042 case PUBKEY_ALGO_ECDSA:
2043 case PUBKEY_ALGO_ECDH:
2049 case PUBKEY_ALGO_EDDSA:
2055 case PUBKEY_ALGO_RSA:
2060 tty_printf(_("%s keys may be between %u and %u bits long.\n"),
2061 openpgp_pk_algo_name (algo), min, max);
2065 char *prompt, *answer;
2068 prompt = xasprintf (_("What keysize do you want "
2069 "for the subkey? (%u) "), def);
2071 prompt = xasprintf (_("What keysize do you want? (%u) "), def);
2072 answer = cpr_get ("keygen.size", prompt);
2074 nbits = *answer? atoi (answer): def;
2078 if(nbits<min || nbits>max)
2079 tty_printf(_("%s keysizes must be in the range %u-%u\n"),
2080 openpgp_pk_algo_name (algo), min, max);
2085 tty_printf (_("Requested keysize is %u bits\n"), nbits);
2088 if (algo == PUBKEY_ALGO_DSA && (nbits % 64))
2090 nbits = ((nbits + 63) / 64) * 64;
2092 tty_printf (_("rounded up to %u bits\n"), nbits);
2094 else if (algo == PUBKEY_ALGO_EDDSA)
2096 if (nbits != 255 && nbits != 441)
2103 tty_printf (_("rounded to %u bits\n"), nbits);
2106 else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA)
2108 if (nbits != 256 && nbits != 384 && nbits != 521)
2112 else if (nbits < 384)
2117 tty_printf (_("rounded to %u bits\n"), nbits);
2120 else if ((nbits % 32))
2122 nbits = ((nbits + 31) / 32) * 32;
2124 tty_printf (_("rounded up to %u bits\n"), nbits );
2131 /* Ask for the curve. ALGO is the selected algorithm which this
2132 function may adjust. Returns a malloced string with the name of
2133 the curve. BOTH tells that gpg creates a primary and subkey. */
2135 ask_curve (int *algo, int *subkey_algo)
2142 const char *pretty_name;
2145 { "Curve25519", 0, 0, 1, "Curve 25519" },
2147 #if GPG_USE_ECDSA || GPG_USE_ECDH
2148 { "NIST P-256", 0, 1, 0, },
2149 { "NIST P-384", 0, 0, 0, },
2150 { "NIST P-521", 0, 1, 0, },
2151 { "brainpoolP256r1", 0, 1, 0, "Brainpool P-256" },
2152 { "brainpoolP384r1", 0, 1, 0, "Brainpool P-384" },
2153 { "brainpoolP512r1", 0, 1, 0, "Brainpool P-512" },
2154 { "secp256k1", 0, 1, 0 },
2159 char *result = NULL;
2160 gcry_sexp_t keyparms;
2162 tty_printf (_("Please select which elliptic curve you want:\n"));
2166 for (idx=0; idx < DIM(curves); idx++)
2170 curves[idx].available = 0;
2171 if (!opt.expert && curves[idx].expert_only)
2174 /* FIXME: The strcmp below is a temporary hack during
2175 development. It shall be removed as soon as we have proper
2176 Curve25519 support in Libgcrypt. */
2177 gcry_sexp_release (keyparms);
2178 rc = gcry_sexp_build (&keyparms, NULL,
2179 "(public-key(ecc(curve %s)))",
2180 (!strcmp (curves[idx].name, "Curve25519")
2181 ? "Ed25519" : curves[idx].name));
2184 if (!gcry_pk_get_curve (keyparms, 0, NULL))
2186 if (subkey_algo && curves[idx].fix_curve)
2188 /* Both Curve 25519 keys are to be created. Check that
2189 Libgcrypt also supports the real Curve25519. */
2190 gcry_sexp_release (keyparms);
2191 rc = gcry_sexp_build (&keyparms, NULL,
2192 "(public-key(ecc(curve %s)))",
2196 if (!gcry_pk_get_curve (keyparms, 0, NULL))
2200 curves[idx].available = 1;
2201 tty_printf (" (%d) %s\n", idx + 1,
2202 curves[idx].pretty_name?
2203 curves[idx].pretty_name:curves[idx].name);
2205 gcry_sexp_release (keyparms);
2210 answer = cpr_get ("keygen.curve", _("Your selection? "));
2212 idx = *answer? atoi (answer) : 1;
2213 if (*answer && !idx)
2215 /* See whether the user entered the name of the curve. */
2216 for (idx=0; idx < DIM(curves); idx++)
2218 if (!opt.expert && curves[idx].expert_only)
2220 if (!stricmp (curves[idx].name, answer)
2221 || (curves[idx].pretty_name
2222 && !stricmp (curves[idx].pretty_name, answer)))
2225 if (idx == DIM(curves))
2232 if (idx < 0 || idx >= DIM (curves) || !curves[idx].available)
2233 tty_printf (_("Invalid selection.\n"));
2236 if (curves[idx].fix_curve)
2238 log_info ("WARNING: Curve25519 is not yet part of the"
2239 " OpenPGP standard.\n");
2241 if (!cpr_get_answer_is_yes("experimental_curve.override",
2242 "Use this curve anyway? (y/N) ") )
2246 /* If the user selected a signing algorithm and Curve25519
2247 we need to update the algo and and the curve name. */
2248 if ((*algo == PUBKEY_ALGO_ECDSA || *algo == PUBKEY_ALGO_EDDSA)
2249 && curves[idx].fix_curve)
2251 if (subkey_algo && *subkey_algo == PUBKEY_ALGO_ECDSA)
2253 *subkey_algo = PUBKEY_ALGO_EDDSA;
2254 result = xstrdup ("Ed25519");
2256 *algo = PUBKEY_ALGO_EDDSA;
2257 result = xstrdup ("Ed25519");
2260 result = xstrdup (curves[idx].name);
2266 result = xstrdup (curves[0].name);
2273 * Parse an expire string and return its value in seconds.
2274 * Returns (u32)-1 on error.
2275 * This isn't perfect since scan_isodatestr returns unix time, and
2276 * OpenPGP actually allows a 32-bit time *plus* a 32-bit offset.
2277 * Because of this, we only permit setting expirations up to 2106, but
2278 * OpenPGP could theoretically allow up to 2242. I think we'll all
2279 * just cope for the next few years until we get a 64-bit time_t or
2283 parse_expire_string( const char *string )
2288 u32 curtime = make_timestamp ();
2293 else if (!strncmp (string, "seconds=", 8))
2294 seconds = atoi (string+8);
2295 else if ((abs_date = scan_isodatestr(string))
2296 && (abs_date+86400/2) > curtime)
2297 seconds = (abs_date+86400/2) - curtime;
2298 else if ((tt = isotime2epoch (string)) != (time_t)(-1))
2299 seconds = (u32)tt - curtime;
2300 else if ((mult = check_valid_days (string)))
2301 seconds = atoi (string) * 86400L * mult;
2303 seconds = (u32)(-1);
2308 /* Parsean Creation-Date string which is either "1986-04-26" or
2309 "19860426T042640". Returns 0 on error. */
2311 parse_creation_string (const char *string)
2317 else if ( !strncmp (string, "seconds=", 8) )
2318 seconds = atoi (string+8);
2319 else if ( !(seconds = scan_isodatestr (string)))
2321 time_t tmp = isotime2epoch (string);
2322 seconds = (tmp == (time_t)(-1))? 0 : tmp;
2328 /* object == 0 for a key, and 1 for a sig */
2330 ask_expire_interval(int object,const char *def_expire)
2340 tty_printf(_("Please specify how long the key should be valid.\n"
2341 " 0 = key does not expire\n"
2342 " <n> = key expires in n days\n"
2343 " <n>w = key expires in n weeks\n"
2344 " <n>m = key expires in n months\n"
2345 " <n>y = key expires in n years\n"));
2351 tty_printf(_("Please specify how long the signature should be valid.\n"
2352 " 0 = signature does not expire\n"
2353 " <n> = signature expires in n days\n"
2354 " <n>w = signature expires in n weeks\n"
2355 " <n>m = signature expires in n months\n"
2356 " <n>y = signature expires in n years\n"));
2363 /* Note: The elgamal subkey for DSA has no expiration date because
2364 * it must be signed with the DSA key and this one has the expiration
2374 answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
2379 #define PROMPTSTRING _("Signature is valid for? (%s) ")
2380 /* This will actually end up larger than necessary because
2381 of the 2 bytes for '%s' */
2382 prompt=xmalloc(strlen(PROMPTSTRING)+strlen(def_expire)+1);
2383 sprintf(prompt,PROMPTSTRING,def_expire);
2386 answer = cpr_get("siggen.valid",prompt);
2390 answer=xstrdup(def_expire);
2393 trim_spaces(answer);
2394 curtime = make_timestamp ();
2395 interval = parse_expire_string( answer );
2396 if( interval == (u32)-1 )
2398 tty_printf(_("invalid value\n"));
2404 tty_printf((object==0)
2405 ? _("Key does not expire at all\n")
2406 : _("Signature does not expire at all\n"));
2410 tty_printf(object==0
2411 ? _("Key expires at %s\n")
2412 : _("Signature expires at %s\n"),
2413 asctimestamp((ulong)(curtime + interval) ) );
2414 #if SIZEOF_TIME_T <= 4 && !defined (HAVE_UNSIGNED_TIME_T)
2415 if ( (time_t)((ulong)(curtime+interval)) < 0 )
2416 tty_printf (_("Your system can't display dates beyond 2038.\n"
2417 "However, it will be correctly handled up to"
2420 #endif /*SIZEOF_TIME_T*/
2421 if ( (time_t)((unsigned long)(curtime+interval)) < curtime )
2423 tty_printf (_("invalid value\n"));
2428 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
2429 _("Is this correct? (y/N) ")) )
2440 u32 x = ask_expire_interval(0,NULL);
2441 return x? make_timestamp() + x : 0;
2446 static PKT_user_id *
2447 uid_from_string (const char *string)
2452 n = strlen (string);
2453 uid = xmalloc_clear (sizeof *uid + n);
2455 strcpy (uid->name, string);
2461 /* Return true if the user id UID already exists in the keyblock. */
2463 uid_already_in_keyblock (kbnode_t keyblock, const char *uid)
2465 PKT_user_id *uidpkt = uid_from_string (uid);
2469 for (node=keyblock; node && !result; node=node->next)
2470 if (!is_deleted_kbnode (node)
2471 && node->pkt->pkttype == PKT_USER_ID
2472 && !cmp_user_ids (uidpkt, node->pkt->pkt.user_id))
2474 free_user_id (uidpkt);
2479 /* Ask for a user ID. With a MODE of 1 an extra help prompt is
2480 printed for use during a new key creation. If KEYBLOCK is not NULL
2481 the function prevents the creation of an already existing user
2482 ID. IF FULL is not set some prompts are not shown. */
2484 ask_user_id (int mode, int full, KBNODE keyblock)
2487 char *aname, *acomment, *amail, *uid;
2491 /* TRANSLATORS: This is the new string telling the user what
2492 gpg is now going to do (i.e. ask for the parts of the user
2493 ID). Note that if you do not translate this string, a
2494 different string will be used, which might still have
2495 a correct translation. */
2498 "GnuPG needs to construct a user ID to identify your key.\n"
2500 const char *s2 = _(s1);
2502 if (!strcmp (s1, s2))
2504 /* There is no translation for the string thus we to use
2505 the old info text. gettext has no way to tell whether
2506 a translation is actually available, thus we need to
2507 to compare again. */
2508 /* TRANSLATORS: This string is in general not anymore used
2509 but you should keep your existing translation. In case
2510 the new string is not translated this old string will
2512 const char *s3 = N_("\n"
2513 "You need a user ID to identify your key; "
2514 "the software constructs the user ID\n"
2515 "from the Real Name, Comment and Email Address in this form:\n"
2516 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n");
2517 const char *s4 = _(s3);
2518 if (strcmp (s3, s4))
2519 s2 = s3; /* A translation exists - use it. */
2521 tty_printf ("%s", s2) ;
2523 uid = aname = acomment = amail = NULL;
2531 aname = cpr_get("keygen.name",_("Real name: "));
2535 if( opt.allow_freeform_uid )
2538 if( strpbrk( aname, "<>" ) )
2539 tty_printf(_("Invalid character in name\n"));
2540 else if( digitp(aname) )
2541 tty_printf(_("Name may not start with a digit\n"));
2542 else if( strlen(aname) < 5 )
2543 tty_printf(_("Name must be at least 5 characters long\n"));
2551 amail = cpr_get("keygen.email",_("Email address: "));
2554 if( !*amail || opt.allow_freeform_uid )
2555 break; /* no email address is okay */
2556 else if ( !is_valid_mailbox (amail) )
2557 tty_printf(_("Not a valid email address\n"));
2566 acomment = cpr_get("keygen.comment",_("Comment: "));
2567 trim_spaces(acomment);
2570 break; /* no comment is okay */
2571 else if( strpbrk( acomment, "()" ) )
2572 tty_printf(_("Invalid character in comment\n"));
2579 acomment = xstrdup ("");
2585 uid = p = xmalloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
2586 p = stpcpy(p, aname );
2588 p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
2590 p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
2592 /* Append a warning if the RNG is switched into fake mode. */
2593 if ( random_is_faked () )
2594 strcpy(p, " (insecure!)" );
2596 /* print a note in case that UTF8 mapping has to be done */
2597 for(p=uid; *p; p++ ) {
2599 tty_printf(_("You are using the '%s' character set.\n"),
2600 get_native_charset() );
2605 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
2607 if( !*amail && !opt.allow_freeform_uid
2608 && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
2610 tty_printf(_("Please don't put the email address "
2611 "into the real name or the comment\n") );
2614 if (!fail && keyblock)
2616 if (uid_already_in_keyblock (keyblock, uid))
2618 tty_printf (_("Such a user ID already exists on this key!\n"));
2624 /* TRANSLATORS: These are the allowed answers in
2625 lower and uppercase. Below you will find the matching
2626 string which should be translated accordingly and the
2627 letter changed to match the one in the answer string.
2632 o = Okay (ready, continue)
2635 const char *ansstr = _("NnCcEeOoQq");
2637 if( strlen(ansstr) != 10 )
2639 if( cpr_enabled() ) {
2640 answer = xstrdup (ansstr + (fail?8:6));
2644 answer = cpr_get("keygen.userid.cmd", fail?
2645 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
2646 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
2650 answer = cpr_get("keygen.userid.cmd", fail?
2651 _("Change (N)ame, (E)mail, or (Q)uit? ") :
2652 _("Change (N)ame, (E)mail, or (O)kay/(Q)uit? "));
2655 if( strlen(answer) > 1 )
2657 else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
2658 xfree(aname); aname = NULL;
2661 else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
2662 xfree(acomment); acomment = NULL;
2665 else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
2666 xfree(amail); amail = NULL;
2669 else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
2671 tty_printf(_("Please correct the error first\n"));
2674 xfree(aname); aname = NULL;
2675 xfree(acomment); acomment = NULL;
2676 xfree(amail); amail = NULL;
2680 else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
2681 xfree(aname); aname = NULL;
2682 xfree(acomment); acomment = NULL;
2683 xfree(amail); amail = NULL;
2684 xfree(uid); uid = NULL;
2690 if (!amail && !acomment)
2692 xfree(uid); uid = NULL;
2695 char *p = native_to_utf8( uid );
2703 /* MODE 0 - standard
2704 1 - Ask for passphrase of the card backup key. */
2707 do_ask_passphrase (STRING2KEY **ret_s2k, int mode, int *r_canceled)
2711 const char *errtext = NULL;
2712 const char *custdesc = NULL;
2714 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
2717 custdesc = _("Please enter a passphrase to protect the off-card "
2718 "backup of the new encryption key.");
2720 s2k = xmalloc_secure( sizeof *s2k );
2722 s2k->mode = opt.s2k_mode;
2723 s2k->hash_algo = S2K_DIGEST_ALGO;
2724 dek = passphrase_to_dek_ext (NULL, 0, opt.s2k_cipher_algo, s2k, 2,
2725 errtext, custdesc, NULL, r_canceled);
2726 if (!dek && *r_canceled) {
2727 xfree(dek); dek = NULL;
2728 xfree(s2k); s2k = NULL;
2732 errtext = N_("passphrase not correctly repeated; try again");
2733 tty_printf(_("%s.\n"), _(errtext));
2735 else if( !dek->keylen ) {
2736 xfree(dek); dek = NULL;
2737 xfree(s2k); s2k = NULL;
2739 "You don't want a passphrase - this is probably a *bad* idea!\n"
2740 "I will do it anyway. You can change your passphrase at any time,\n"
2741 "using this program with the option \"--edit-key\".\n\n"));
2753 /* Basic key generation. Here we divert to the actual generation
2754 routines based on the requested algorithm. */
2756 do_create (int algo, unsigned int nbits, const char *curve, KBNODE pub_root,
2757 u32 timestamp, u32 expiredate, int is_subkey,
2758 int keygen_flags, const char *passphrase, char **cache_nonce_addr)
2762 /* Fixme: The entropy collecting message should be moved to a
2763 libgcrypt progress handler. */
2766 "We need to generate a lot of random bytes. It is a good idea to perform\n"
2767 "some other action (type on the keyboard, move the mouse, utilize the\n"
2768 "disks) during the prime generation; this gives the random number\n"
2769 "generator a better chance to gain enough entropy.\n") );
2771 if (algo == PUBKEY_ALGO_ELGAMAL_E)
2772 err = gen_elg (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
2773 keygen_flags, passphrase, cache_nonce_addr);
2774 else if (algo == PUBKEY_ALGO_DSA)
2775 err = gen_dsa (nbits, pub_root, timestamp, expiredate, is_subkey,
2776 keygen_flags, passphrase, cache_nonce_addr);
2777 else if (algo == PUBKEY_ALGO_ECDSA
2778 || algo == PUBKEY_ALGO_EDDSA
2779 || algo == PUBKEY_ALGO_ECDH)
2780 err = gen_ecc (algo, curve, pub_root, timestamp, expiredate, is_subkey,
2781 keygen_flags, passphrase, cache_nonce_addr);
2782 else if (algo == PUBKEY_ALGO_RSA)
2783 err = gen_rsa (algo, nbits, pub_root, timestamp, expiredate, is_subkey,
2784 keygen_flags, passphrase, cache_nonce_addr);
2792 /* Generate a new user id packet or return NULL if canceled. If
2793 KEYBLOCK is not NULL the function prevents the creation of an
2794 already existing user ID. If UIDSTR is not NULL the user is not
2795 asked but UIDSTR is used to create the user id packet; if the user
2796 id already exists NULL is returned. UIDSTR is expected to be utf-8
2797 encoded and should have already been checked for a valid length
2800 generate_user_id (KBNODE keyblock, const char *uidstr)
2807 if (uid_already_in_keyblock (keyblock, uidstr))
2808 return NULL; /* Already exists. */
2809 uid = uid_from_string (uidstr);
2813 p = ask_user_id (1, 1, keyblock);
2815 return NULL; /* Canceled. */
2816 uid = uid_from_string (p);
2823 /* Append R to the linked list PARA. */
2825 append_to_parameter (struct para_data_s *para, struct para_data_s *r)
2833 /* Release the parameter list R. */
2835 release_parameter_list (struct para_data_s *r)
2837 struct para_data_s *r2;
2842 if (r->key == pPASSPHRASE && *r->u.value)
2843 wipememory (r->u.value, strlen (r->u.value));
2848 static struct para_data_s *
2849 get_parameter( struct para_data_s *para, enum para_name key )
2851 struct para_data_s *r;
2853 for( r = para; r && r->key != key; r = r->next )
2859 get_parameter_value( struct para_data_s *para, enum para_name key )
2861 struct para_data_s *r = get_parameter( para, key );
2862 return (r && *r->u.value)? r->u.value : NULL;
2866 /* This is similar to get_parameter_value but also returns the empty
2867 string. This is required so that quick_generate_keypair can use an
2868 empty Passphrase to specify no-protection. */
2870 get_parameter_passphrase (struct para_data_s *para)
2872 struct para_data_s *r = get_parameter (para, pPASSPHRASE);
2873 return r ? r->u.value : NULL;
2878 get_parameter_algo( struct para_data_s *para, enum para_name key,
2882 struct para_data_s *r = get_parameter( para, key );
2890 /* Note that we need to handle the ECC algorithms specified as
2891 strings directly because Libgcrypt folds them all to ECC. */
2892 if (!ascii_strcasecmp (r->u.value, "default"))
2894 /* Note: If you change this default algo, remember to change it
2895 also in gpg.c:gpgconf_list. */
2896 i = DEFAULT_STD_ALGO;
2900 else if (digitp (r->u.value))
2901 i = atoi( r->u.value );
2902 else if (!strcmp (r->u.value, "ELG-E")
2903 || !strcmp (r->u.value, "ELG"))
2904 i = PUBKEY_ALGO_ELGAMAL_E;
2905 else if (!ascii_strcasecmp (r->u.value, "EdDSA"))
2906 i = PUBKEY_ALGO_EDDSA;
2907 else if (!ascii_strcasecmp (r->u.value, "ECDSA"))
2908 i = PUBKEY_ALGO_ECDSA;
2909 else if (!ascii_strcasecmp (r->u.value, "ECDH"))
2910 i = PUBKEY_ALGO_ECDH;
2912 i = map_pk_gcry_to_openpgp (gcry_pk_map_name (r->u.value));
2914 if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
2915 i = 0; /* we don't want to allow generation of these algorithms */
2920 * Parse the usage parameter and set the keyflags. Returns -1 on
2921 * error, 0 for no usage given or 1 for usage available.
2924 parse_parameter_usage (const char *fname,
2925 struct para_data_s *para, enum para_name key)
2927 struct para_data_s *r = get_parameter( para, key );
2932 return 0; /* none (this is an optional parameter)*/
2936 while ( (p = strsep (&pn, " \t,")) ) {
2939 else if ( !ascii_strcasecmp (p, "sign") )
2940 use |= PUBKEY_USAGE_SIG;
2941 else if ( !ascii_strcasecmp (p, "encrypt") )
2942 use |= PUBKEY_USAGE_ENC;
2943 else if ( !ascii_strcasecmp (p, "auth") )
2944 use |= PUBKEY_USAGE_AUTH;
2946 log_error("%s:%d: invalid usage list\n", fname, r->lnr );
2947 return -1; /* error */
2955 parse_revocation_key (const char *fname,
2956 struct para_data_s *para, enum para_name key)
2958 struct para_data_s *r = get_parameter( para, key );
2959 struct revocation_key revkey;
2964 return 0; /* none (this is an optional parameter) */
2969 revkey.algid=atoi(pn);
2973 /* Skip to the fpr */
2974 while(*pn && *pn!=':')
2982 for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
2984 int c=hextobyte(pn);
2991 /* skip to the tag */
2992 while(*pn && *pn!='s' && *pn!='S')
2995 if(ascii_strcasecmp(pn,"sensitive")==0)
2998 memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
3003 log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
3004 return -1; /* error */
3009 get_parameter_u32( struct para_data_s *para, enum para_name key )
3011 struct para_data_s *r = get_parameter( para, key );
3015 if( r->key == pKEYCREATIONDATE )
3016 return r->u.creation;
3017 if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
3019 if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
3022 return (unsigned int)strtoul( r->u.value, NULL, 10 );
3026 get_parameter_uint( struct para_data_s *para, enum para_name key )
3028 return get_parameter_u32( para, key );
3031 static struct revocation_key *
3032 get_parameter_revkey( struct para_data_s *para, enum para_name key )
3034 struct para_data_s *r = get_parameter( para, key );
3035 return r? &r->u.revkey : NULL;
3039 proc_parameter_file( struct para_data_s *para, const char *fname,
3040 struct output_control_s *outctrl, int card )
3042 struct para_data_s *r;
3043 const char *s1, *s2, *s3;
3047 int have_user_id = 0;
3050 /* Check that we have all required parameters. */
3051 r = get_parameter( para, pKEYTYPE );
3054 algo = get_parameter_algo (para, pKEYTYPE, &is_default);
3055 if (openpgp_pk_test_algo2 (algo, PUBKEY_USAGE_SIG))
3057 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
3063 log_error ("%s: no Key-Type specified\n",fname);
3067 err = parse_parameter_usage (fname, para, pKEYUSAGE);
3070 /* Default to algo capabilities if key-usage is not provided and
3071 no default algorithm has been requested. */
3072 r = xmalloc_clear(sizeof(*r));
3074 r->u.usage = (is_default
3075 ? (PUBKEY_USAGE_CERT | PUBKEY_USAGE_SIG)
3076 : openpgp_pk_algo_usage(algo));
3077 append_to_parameter (para, r);
3083 r = get_parameter (para, pKEYUSAGE);
3084 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
3086 log_error ("%s:%d: specified Key-Usage not allowed for algo %d\n",
3087 fname, r->lnr, algo);
3093 r = get_parameter( para, pSUBKEYTYPE );
3096 algo = get_parameter_algo (para, pSUBKEYTYPE, &is_default);
3097 if (openpgp_pk_test_algo (algo))
3099 log_error ("%s:%d: invalid algorithm\n", fname, r->lnr );
3103 err = parse_parameter_usage (fname, para, pSUBKEYUSAGE);
3106 /* Default to algo capabilities if subkey-usage is not
3108 r = xmalloc_clear (sizeof(*r));
3109 r->key = pSUBKEYUSAGE;
3110 r->u.usage = (is_default
3112 : openpgp_pk_algo_usage (algo));
3113 append_to_parameter (para, r);
3119 r = get_parameter (para, pSUBKEYUSAGE);
3120 if (r && (r->u.usage & ~openpgp_pk_algo_usage (algo)))
3122 log_error ("%s:%d: specified Subkey-Usage not allowed"
3123 " for algo %d\n", fname, r->lnr, algo);
3130 if( get_parameter_value( para, pUSERID ) )
3134 /* create the formatted user ID */
3135 s1 = get_parameter_value( para, pNAMEREAL );
3136 s2 = get_parameter_value( para, pNAMECOMMENT );
3137 s3 = get_parameter_value( para, pNAMEEMAIL );
3138 if( s1 || s2 || s3 )
3140 n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
3141 r = xmalloc_clear( sizeof *r + n + 20 );
3147 p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
3149 p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
3150 append_to_parameter (para, r);
3157 log_error("%s: no User-ID specified\n",fname);
3161 /* Set preferences, if any. */
3162 keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
3164 /* Set keyserver, if any. */
3165 s1=get_parameter_value( para, pKEYSERVER );
3168 struct keyserver_spec *spec;
3170 spec = parse_keyserver_uri (s1, 1);
3173 free_keyserver_spec(spec);
3174 opt.def_keyserver_url=s1;
3178 log_error("%s:%d: invalid keyserver url\n", fname, r->lnr );
3183 /* Set revoker, if any. */
3184 if (parse_revocation_key (fname, para, pREVOKER))
3188 /* Make KEYCREATIONDATE from Creation-Date. */
3189 r = get_parameter (para, pCREATIONDATE);
3190 if (r && *r->u.value)
3194 seconds = parse_creation_string (r->u.value);
3197 log_error ("%s:%d: invalid creation date\n", fname, r->lnr );
3200 r->u.creation = seconds;
3201 r->key = pKEYCREATIONDATE; /* Change that entry. */
3204 /* Make KEYEXPIRE from Expire-Date. */
3205 r = get_parameter( para, pEXPIREDATE );
3206 if( r && *r->u.value )
3210 seconds = parse_expire_string( r->u.value );
3211 if( seconds == (u32)-1 )
3213 log_error("%s:%d: invalid expire date\n", fname, r->lnr );
3216 r->u.expire = seconds;
3217 r->key = pKEYEXPIRE; /* change hat entry */
3218 /* also set it for the subkey */
3219 r = xmalloc_clear( sizeof *r + 20 );
3220 r->key = pSUBKEYEXPIRE;
3221 r->u.expire = seconds;
3222 append_to_parameter (para, r);
3225 do_generate_keypair( para, outctrl, card );
3231 * Kludge to allow non interactive key generation controlled
3232 * by a parameter file.
3233 * Note, that string parameters are expected to be in UTF-8
3236 read_parameter_file( const char *fname )
3238 static struct { const char *name;
3241 { "Key-Type", pKEYTYPE},
3242 { "Key-Length", pKEYLENGTH },
3243 { "Key-Curve", pKEYCURVE },
3244 { "Key-Usage", pKEYUSAGE },
3245 { "Subkey-Type", pSUBKEYTYPE },
3246 { "Subkey-Length", pSUBKEYLENGTH },
3247 { "Subkey-Curve", pSUBKEYCURVE },
3248 { "Subkey-Usage", pSUBKEYUSAGE },
3249 { "Name-Real", pNAMEREAL },
3250 { "Name-Email", pNAMEEMAIL },
3251 { "Name-Comment", pNAMECOMMENT },
3252 { "Expire-Date", pEXPIREDATE },
3253 { "Creation-Date", pCREATIONDATE },
3254 { "Passphrase", pPASSPHRASE },
3255 { "Preferences", pPREFERENCES },
3256 { "Revoker", pREVOKER },
3257 { "Handle", pHANDLE },
3258 { "Keyserver", pKEYSERVER },
3263 unsigned int maxlen, nline;
3266 const char *err = NULL;
3267 struct para_data_s *para, *r;
3269 struct output_control_s outctrl;
3271 memset( &outctrl, 0, sizeof( outctrl ) );
3272 outctrl.pub.afx = new_armor_context ();
3274 if( !fname || !*fname)
3277 fp = iobuf_open (fname);
3278 if (fp && is_secured_file (iobuf_get_fd (fp)))
3282 gpg_err_set_errno (EPERM);
3285 log_error (_("can't open '%s': %s\n"), fname, strerror(errno) );
3288 iobuf_ioctl (fp, IOBUF_IOCTL_NO_CACHE, 1, NULL);
3295 while ( iobuf_read_line (fp, &line, &nline, &maxlen) ) {
3296 char *keyword, *value;
3300 err = "line too long";
3303 for( p = line; isspace(*(byte*)p); p++ )
3305 if( !*p || *p == '#' )
3308 if( *keyword == '%' ) {
3309 for( ; !isspace(*(byte*)p); p++ )
3313 for( ; isspace(*(byte*)p); p++ )
3316 trim_trailing_ws( value, strlen(value) );
3317 if( !ascii_strcasecmp( keyword, "%echo" ) )
3318 log_info("%s\n", value );
3319 else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
3321 else if( !ascii_strcasecmp( keyword, "%ask-passphrase" ) )
3322 ; /* Dummy for backward compatibility. */
3323 else if( !ascii_strcasecmp( keyword, "%no-ask-passphrase" ) )
3324 ; /* Dummy for backward compatibility. */
3325 else if( !ascii_strcasecmp( keyword, "%no-protection" ) )
3326 outctrl.keygen_flags |= KEYGEN_FLAG_NO_PROTECTION;
3327 else if( !ascii_strcasecmp( keyword, "%transient-key" ) )
3328 outctrl.keygen_flags |= KEYGEN_FLAG_TRANSIENT_KEY;
3329 else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
3331 if (proc_parameter_file( para, fname, &outctrl, 0 ))
3332 print_status_key_not_created
3333 (get_parameter_value (para, pHANDLE));
3334 release_parameter_list( para );
3337 else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
3338 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
3339 ; /* still the same file - ignore it */
3341 xfree( outctrl.pub.newfname );
3342 outctrl.pub.newfname = xstrdup( value );
3343 outctrl.use_files = 1;
3346 else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
3347 /* Ignore this command. */
3350 log_info("skipping control '%s' (%s)\n", keyword, value );
3357 if( !(p = strchr( p, ':' )) || p == keyword ) {
3358 err = "missing colon";
3363 for( ; isspace(*(byte*)p); p++ )
3366 err = "missing argument";
3370 trim_trailing_ws( value, strlen(value) );
3372 for(i=0; keywords[i].name; i++ ) {
3373 if( !ascii_strcasecmp( keywords[i].name, keyword ) )
3376 if( !keywords[i].name ) {
3377 err = "unknown keyword";
3380 if( keywords[i].key != pKEYTYPE && !para ) {
3381 err = "parameter block does not start with \"Key-Type\"";
3385 if( keywords[i].key == pKEYTYPE && para ) {
3387 if (proc_parameter_file( para, fname, &outctrl, 0 ))
3388 print_status_key_not_created
3389 (get_parameter_value (para, pHANDLE));
3390 release_parameter_list( para );
3394 for( r = para; r; r = r->next ) {
3395 if( r->key == keywords[i].key )
3399 err = "duplicate keyword";
3403 r = xmalloc_clear( sizeof *r + strlen( value ) );
3405 r->key = keywords[i].key;
3406 strcpy( r->u.value, value );
3411 log_error("%s:%d: %s\n", fname, lnr, err );
3412 else if( iobuf_error (fp) ) {
3413 log_error("%s:%d: read error\n", fname, lnr);
3417 if (proc_parameter_file( para, fname, &outctrl, 0 ))
3418 print_status_key_not_created (get_parameter_value (para, pHANDLE));
3421 if( outctrl.use_files ) { /* close open streams */
3422 iobuf_close( outctrl.pub.stream );
3424 /* Must invalidate that ugly cache to actually close it. */
3425 if (outctrl.pub.fname)
3426 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
3427 0, (char*)outctrl.pub.fname);
3429 xfree( outctrl.pub.fname );
3430 xfree( outctrl.pub.newfname );
3433 release_parameter_list( para );
3435 release_armor_context (outctrl.pub.afx);
3439 /* Helper for quick_generate_keypair. */
3440 static struct para_data_s *
3441 quickgen_set_para (struct para_data_s *para, int for_subkey,
3442 int algo, int nbits, const char *curve)
3444 struct para_data_s *r;
3446 r = xmalloc_clear (sizeof *r + 20);
3447 r->key = for_subkey? pSUBKEYUSAGE : pKEYUSAGE;
3448 strcpy (r->u.value, for_subkey ? "encrypt" : "sign");
3451 r = xmalloc_clear (sizeof *r + 20);
3452 r->key = for_subkey? pSUBKEYTYPE : pKEYTYPE;
3453 sprintf (r->u.value, "%d", algo);
3459 r = xmalloc_clear (sizeof *r + strlen (curve));
3460 r->key = for_subkey? pSUBKEYCURVE : pKEYCURVE;
3461 strcpy (r->u.value, curve);
3467 r = xmalloc_clear (sizeof *r + 20);
3468 r->key = for_subkey? pSUBKEYLENGTH : pKEYLENGTH;
3469 sprintf (r->u.value, "%u", nbits);
3479 * Unattended generation of a standard key.
3482 quick_generate_keypair (const char *uid)
3485 struct para_data_s *para = NULL;
3486 struct para_data_s *r;
3487 struct output_control_s outctrl;
3490 memset (&outctrl, 0, sizeof outctrl);
3492 use_tty = (!opt.batch && !opt.answer_yes
3494 && gnupg_isatty (fileno (stdin))
3495 && gnupg_isatty (fileno (stdout))
3496 && gnupg_isatty (fileno (stderr)));
3498 r = xmalloc_clear (sizeof *r + strlen (uid));
3500 strcpy (r->u.value, uid);
3504 uid = trim_spaces (r->u.value);
3505 if (!*uid || (!opt.allow_freeform_uid && !is_valid_user_id (uid)))
3507 log_error (_("Key generation failed: %s\n"),
3508 gpg_strerror (GPG_ERR_INV_USER_ID));
3512 /* If gpg is directly used on the console ask whether a key with the
3513 given user id shall really be created. */
3516 tty_printf (_("About to create a key for:\n \"%s\"\n\n"), uid);
3517 if (!cpr_get_answer_is_yes_def ("quick_keygen.okay",
3518 _("Continue? (Y/n) "), 1))
3522 /* Check whether such a user ID already exists. */
3525 KEYDB_SEARCH_DESC desc;
3527 memset (&desc, 0, sizeof desc);
3528 desc.mode = KEYDB_SEARCH_MODE_EXACT;
3531 kdbhd = keydb_new ();
3532 err = keydb_search (kdbhd, &desc, 1, NULL);
3533 keydb_release (kdbhd);
3534 if (gpg_err_code (err) != GPG_ERR_NOT_FOUND)
3536 log_info (_("A key for \"%s\" already exists\n"), uid);
3540 || !cpr_get_answer_is_yes_def ("quick_keygen.force",
3541 _("Create anyway? (y/N) "), 0))
3543 log_inc_errorcount (); /* we used log_info */
3546 log_info (_("creating anyway\n"));
3550 para = quickgen_set_para (para, 0,
3551 DEFAULT_STD_ALGO, DEFAULT_STD_KEYSIZE,
3553 para = quickgen_set_para (para, 1,
3554 DEFAULT_STD_SUBALGO, DEFAULT_STD_SUBKEYSIZE,
3555 DEFAULT_STD_SUBCURVE);
3557 /* If the pinentry loopback mode is not and we have a static
3558 passphrase (i.e. set with --passphrase{,-fd,-file} while in batch
3559 mode), we use that passphrase for the new key. */
3560 if (opt.pinentry_mode != PINENTRY_MODE_LOOPBACK
3561 && have_static_passphrase ())
3563 const char *s = get_static_passphrase ();
3565 r = xmalloc_clear (sizeof *r + strlen (s));
3566 r->key = pPASSPHRASE;
3567 strcpy (r->u.value, s);
3572 proc_parameter_file (para, "[internal]", &outctrl, 0);
3574 release_parameter_list (para);
3579 * Generate a keypair (fname is only used in batch mode) If
3580 * CARD_SERIALNO is not NULL the function will create the keys on an
3581 * OpenPGP Card. If CARD_BACKUP_KEY has been set and CARD_SERIALNO is
3582 * NOT NULL, the encryption key for the card is generated on the host,
3583 * imported to the card and a backup file created by gpg-agent. If
3584 * FULL is not set only the basic prompts are used (except for batch
3588 generate_keypair (ctrl_t ctrl, int full, const char *fname,
3589 const char *card_serialno, int card_backup_key)
3597 struct para_data_s *para = NULL;
3598 struct para_data_s *r;
3599 struct output_control_s outctrl;
3601 #ifndef ENABLE_CARD_SUPPORT
3602 (void)card_backup_key;
3605 memset( &outctrl, 0, sizeof( outctrl ) );
3607 if (opt.batch && card_serialno)
3609 /* We don't yet support unattended key generation. */
3610 log_error (_("can't do this in batch mode\n"));
3616 read_parameter_file( fname );
3622 #ifdef ENABLE_CARD_SUPPORT
3623 r = xcalloc (1, sizeof *r + strlen (card_serialno) );
3625 strcpy( r->u.value, card_serialno);
3629 algo = PUBKEY_ALGO_RSA;
3631 r = xcalloc (1, sizeof *r + 20 );
3633 sprintf( r->u.value, "%d", algo );
3636 r = xcalloc (1, sizeof *r + 20 );
3638 strcpy (r->u.value, "sign");
3642 r = xcalloc (1, sizeof *r + 20 );
3643 r->key = pSUBKEYTYPE;
3644 sprintf( r->u.value, "%d", algo );
3647 r = xcalloc (1, sizeof *r + 20 );
3648 r->key = pSUBKEYUSAGE;
3649 strcpy (r->u.value, "encrypt");
3653 r = xcalloc (1, sizeof *r + 20 );
3654 r->key = pAUTHKEYTYPE;
3655 sprintf( r->u.value, "%d", algo );
3659 if (card_backup_key)
3661 r = xcalloc (1, sizeof *r + 1);
3662 r->key = pCARDBACKUPKEY;
3663 strcpy (r->u.value, "1");
3667 #endif /*ENABLE_CARD_SUPPORT*/
3669 else if (full) /* Full featured key generation. */
3674 /* Fixme: To support creating a primary key by keygrip we better
3675 also define the keyword for the parameter file. Note that
3676 the subkey case will never be asserted if a keygrip has been
3678 algo = ask_algo (ctrl, 0, &subkey_algo, &use, NULL);
3681 /* Create primary and subkey at once. */
3683 if (algo == PUBKEY_ALGO_ECDSA
3684 || algo == PUBKEY_ALGO_EDDSA
3685 || algo == PUBKEY_ALGO_ECDH)
3687 curve = ask_curve (&algo, &subkey_algo);
3688 r = xmalloc_clear( sizeof *r + 20 );
3690 sprintf( r->u.value, "%d", algo);
3694 r = xmalloc_clear (sizeof *r + strlen (curve));
3696 strcpy (r->u.value, curve);
3702 r = xmalloc_clear( sizeof *r + 20 );
3704 sprintf( r->u.value, "%d", algo);
3707 nbits = ask_keysize (algo, 0);
3708 r = xmalloc_clear( sizeof *r + 20 );
3709 r->key = pKEYLENGTH;
3710 sprintf( r->u.value, "%u", nbits);
3714 r = xmalloc_clear( sizeof *r + 20 );
3716 strcpy( r->u.value, "sign" );
3720 r = xmalloc_clear( sizeof *r + 20 );
3721 r->key = pSUBKEYTYPE;
3722 sprintf( r->u.value, "%d", subkey_algo);
3725 r = xmalloc_clear( sizeof *r + 20 );
3726 r->key = pSUBKEYUSAGE;
3727 strcpy( r->u.value, "encrypt" );
3731 if (algo == PUBKEY_ALGO_ECDSA
3732 || algo == PUBKEY_ALGO_EDDSA
3733 || algo == PUBKEY_ALGO_ECDH)
3735 if (algo == PUBKEY_ALGO_EDDSA
3736 && subkey_algo == PUBKEY_ALGO_ECDH)
3738 /* Need to switch to a different curve for the
3741 curve = xstrdup ("Curve25519");
3743 r = xmalloc_clear (sizeof *r + strlen (curve));
3744 r->key = pSUBKEYCURVE;
3745 strcpy (r->u.value, curve);
3750 else /* Create only a single key. */
3752 /* For ECC we need to ask for the curve before storing the
3753 algo because ask_curve may change the algo. */
3754 if (algo == PUBKEY_ALGO_ECDSA
3755 || algo == PUBKEY_ALGO_EDDSA
3756 || algo == PUBKEY_ALGO_ECDH)
3758 curve = ask_curve (&algo, NULL);
3760 r = xmalloc_clear (sizeof *r + strlen (curve));
3762 strcpy (r->u.value, curve);
3767 r = xmalloc_clear( sizeof *r + 20 );
3769 sprintf( r->u.value, "%d", algo );
3775 r = xmalloc_clear( sizeof *r + 25 );
3777 sprintf( r->u.value, "%s%s%s",
3778 (use & PUBKEY_USAGE_SIG)? "sign ":"",
3779 (use & PUBKEY_USAGE_ENC)? "encrypt ":"",
3780 (use & PUBKEY_USAGE_AUTH)? "auth":"" );
3787 if (algo == PUBKEY_ALGO_ECDSA
3788 || algo == PUBKEY_ALGO_EDDSA
3789 || algo == PUBKEY_ALGO_ECDH)
3791 /* The curve has already been set. */
3795 nbits = ask_keysize (both? subkey_algo : algo, nbits);
3796 r = xmalloc_clear( sizeof *r + 20 );
3797 r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
3798 sprintf( r->u.value, "%u", nbits);
3805 else /* Default key generation. */
3807 tty_printf ( _("Note: Use \"%s %s\""
3808 " for a full featured key generation dialog.\n"),
3809 NAME_OF_INSTALLED_GPG, "--full-gen-key" );
3810 para = quickgen_set_para (para, 0,
3811 DEFAULT_STD_ALGO, DEFAULT_STD_KEYSIZE,
3813 para = quickgen_set_para (para, 1,
3814 DEFAULT_STD_SUBALGO, DEFAULT_STD_SUBKEYSIZE,
3815 DEFAULT_STD_SUBCURVE);
3819 expire = full? ask_expire_interval (0, NULL) : 0;
3820 r = xcalloc (1, sizeof *r + 20);
3821 r->key = pKEYEXPIRE;
3822 r->u.expire = expire;
3825 r = xcalloc (1, sizeof *r + 20);
3826 r->key = pSUBKEYEXPIRE;
3827 r->u.expire = expire;
3831 uid = ask_user_id (0, full, NULL);
3834 log_error(_("Key generation canceled.\n"));
3835 release_parameter_list( para );
3838 r = xcalloc (1, sizeof *r + strlen (uid));
3840 strcpy (r->u.value, uid);
3844 proc_parameter_file (para, "[internal]", &outctrl, !!card_serialno);
3845 release_parameter_list (para);
3849 #if 0 /* not required */
3850 /* Generate a raw key and return it as a secret key packet. The
3851 function will ask for the passphrase and return a protected as well
3852 as an unprotected copy of a new secret key packet. 0 is returned
3853 on success and the caller must then free the returned values. */
3855 generate_raw_key (int algo, unsigned int nbits, u32 created_at,
3856 PKT_secret_key **r_sk_unprotected,
3857 PKT_secret_key **r_sk_protected)
3861 STRING2KEY *s2k = NULL;
3862 PKT_secret_key *sk = NULL;
3864 size_t nskey, npkey;
3865 gcry_sexp_t s_parms, s_key;
3868 npkey = pubkey_get_npkey (algo);
3869 nskey = pubkey_get_nskey (algo);
3870 assert (nskey <= PUBKEY_MAX_NSKEY && npkey < nskey);
3875 log_info (_("keysize invalid; using %u bits\n"), nbits );
3880 nbits = ((nbits + 31) / 32) * 32;
3881 log_info(_("keysize rounded up to %u bits\n"), nbits );
3884 dek = do_ask_passphrase (&s2k, 1, &canceled);
3887 rc = gpg_error (GPG_ERR_CANCELED);
3891 sk = xmalloc_clear (sizeof *sk);
3892 sk->timestamp = created_at;
3894 sk->pubkey_algo = algo;
3896 if ( !is_RSA (algo) )
3898 log_error ("only RSA is supported for offline generated keys\n");
3899 rc = gpg_error (GPG_ERR_NOT_IMPLEMENTED);
3902 rc = gcry_sexp_build (&s_parms, NULL,
3903 "(genkey(rsa(nbits %d)))",
3906 log_bug ("gcry_sexp_build failed: %s\n", gpg_strerror (rc));
3907 rc = gcry_pk_genkey (&s_key, s_parms);
3908 gcry_sexp_release (s_parms);
3911 log_error ("gcry_pk_genkey failed: %s\n", gpg_strerror (rc) );
3914 rc = key_from_sexp (sk->skey, s_key, "private-key", "nedpqu");
3915 gcry_sexp_release (s_key);
3918 log_error ("key_from_sexp failed: %s\n", gpg_strerror (rc) );
3922 for (i=npkey; i < nskey; i++)
3923 sk->csum += checksum_mpi (sk->skey[i]);
3925 if (r_sk_unprotected)
3926 *r_sk_unprotected = copy_secret_key (NULL, sk);
3928 rc = genhelp_protect (dek, s2k, sk);
3934 *r_sk_protected = sk;
3940 free_secret_key (sk);
3945 #endif /* ENABLE_CARD_SUPPORT */
3947 /* Create and delete a dummy packet to start off a list of kbnodes. */
3949 start_tree(KBNODE *tree)
3953 pkt=xmalloc_clear(sizeof(*pkt));
3954 pkt->pkttype=PKT_NONE;
3955 *tree=new_kbnode(pkt);
3956 delete_kbnode(*tree);
3961 do_generate_keypair (struct para_data_s *para,
3962 struct output_control_s *outctrl, int card)
3965 KBNODE pub_root = NULL;
3967 PKT_public_key *pri_psk = NULL;
3968 PKT_public_key *sub_psk = NULL;
3969 struct revocation_key *revkey;
3972 char *cache_nonce = NULL;
3974 if (outctrl->dryrun)
3976 log_info("dry-run mode - key generation skipped\n");
3980 if ( outctrl->use_files )
3982 if ( outctrl->pub.newfname )
3984 iobuf_close(outctrl->pub.stream);
3985 outctrl->pub.stream = NULL;
3986 if (outctrl->pub.fname)
3987 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE,
3988 0, (char*)outctrl->pub.fname);
3989 xfree( outctrl->pub.fname );
3990 outctrl->pub.fname = outctrl->pub.newfname;
3991 outctrl->pub.newfname = NULL;
3993 if (is_secured_filename (outctrl->pub.fname) )
3995 outctrl->pub.stream = NULL;
3996 gpg_err_set_errno (EPERM);
3999 outctrl->pub.stream = iobuf_create (outctrl->pub.fname, 0);
4000 if (!outctrl->pub.stream)
4002 log_error(_("can't create '%s': %s\n"), outctrl->pub.newfname,
4008 outctrl->pub.afx->what = 1;
4009 push_armor_filter (outctrl->pub.afx, outctrl->pub.stream);
4012 assert( outctrl->pub.stream );
4014 log_info (_("writing public key to '%s'\n"), outctrl->pub.fname );
4018 /* We create the packets as a tree of kbnodes. Because the
4019 structure we create is known in advance we simply generate a
4020 linked list. The first packet is a dummy packet which we flag as
4021 deleted. The very first packet must always be a KEY packet. */
4023 start_tree (&pub_root);
4025 timestamp = get_parameter_u32 (para, pKEYCREATIONDATE);
4027 timestamp = make_timestamp ();
4029 /* Note that, depending on the backend (i.e. the used scdaemon
4030 version), the card key generation may update TIMESTAMP for each
4031 key. Thus we need to pass TIMESTAMP to all signing function to
4032 make sure that the binding signature is done using the timestamp
4033 of the corresponding (sub)key and not that of the primary key.
4034 An alternative implementation could tell the signing function the
4035 node of the subkey but that is more work than just to pass the
4036 current timestamp. */
4039 err = do_create (get_parameter_algo( para, pKEYTYPE, NULL ),
4040 get_parameter_uint( para, pKEYLENGTH ),
4041 get_parameter_value (para, pKEYCURVE),
4044 get_parameter_u32( para, pKEYEXPIRE ), 0,
4045 outctrl->keygen_flags,
4046 get_parameter_passphrase (para),
4049 err = gen_card_key (PUBKEY_ALGO_RSA, 1, 1, pub_root,
4051 get_parameter_u32 (para, pKEYEXPIRE));
4053 /* Get the pointer to the generated public key packet. */
4056 pri_psk = pub_root->next->pkt->pkt.public_key;
4060 if (!err && (revkey = get_parameter_revkey (para, pREVOKER)))
4061 err = write_direct_sig (pub_root, pri_psk, revkey, timestamp, cache_nonce);
4063 if (!err && (s = get_parameter_value (para, pUSERID)))
4065 write_uid (pub_root, s );
4066 err = write_selfsigs (pub_root, pri_psk,
4067 get_parameter_uint (para, pKEYUSAGE), timestamp,
4071 /* Write the auth key to the card before the encryption key. This
4072 is a partial workaround for a PGP bug (as of this writing, all
4073 versions including 8.1), that causes it to try and encrypt to
4074 the most recent subkey regardless of whether that subkey is
4075 actually an encryption type. In this case, the auth key is an
4076 RSA key so it succeeds. */
4078 if (!err && card && get_parameter (para, pAUTHKEYTYPE))
4080 err = gen_card_key (PUBKEY_ALGO_RSA, 3, 0, pub_root,
4082 get_parameter_u32 (para, pKEYEXPIRE));
4084 err = write_keybinding (pub_root, pri_psk, NULL,
4085 PUBKEY_USAGE_AUTH, timestamp, cache_nonce);
4088 if (!err && get_parameter (para, pSUBKEYTYPE))
4093 err = do_create (get_parameter_algo (para, pSUBKEYTYPE, NULL),
4094 get_parameter_uint (para, pSUBKEYLENGTH),
4095 get_parameter_value (para, pSUBKEYCURVE),
4098 get_parameter_u32 (para, pSUBKEYEXPIRE), 1,
4099 outctrl->keygen_flags,
4100 get_parameter_passphrase (para),
4102 /* Get the pointer to the generated public subkey packet. */
4107 for (node = pub_root; node; node = node->next)
4108 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4109 sub_psk = node->pkt->pkt.public_key;
4115 if ((s = get_parameter_value (para, pCARDBACKUPKEY)))
4117 /* A backup of the encryption key has been requested.
4118 Generate the key in software and import it then to
4119 the card. Write a backup file. */
4120 err = gen_card_key_with_backup
4121 (PUBKEY_ALGO_RSA, 2, 0, pub_root, timestamp,
4122 get_parameter_u32 (para, pKEYEXPIRE), para);
4126 err = gen_card_key (PUBKEY_ALGO_RSA, 2, 0, pub_root,
4128 get_parameter_u32 (para, pKEYEXPIRE));
4133 err = write_keybinding (pub_root, pri_psk, sub_psk,
4134 get_parameter_uint (para, pSUBKEYUSAGE),
4135 timestamp, cache_nonce);
4139 if (!err && outctrl->use_files) /* Direct write to specified files. */
4141 err = write_keyblock (outctrl->pub.stream, pub_root);
4143 log_error ("can't write public key: %s\n", gpg_strerror (err));
4145 else if (!err) /* Write to the standard keyrings. */
4147 KEYDB_HANDLE pub_hd = keydb_new ();
4149 err = keydb_locate_writable (pub_hd);
4151 log_error (_("no writable public keyring found: %s\n"),
4152 gpg_strerror (err));
4154 if (!err && opt.verbose)
4156 log_info (_("writing public key to '%s'\n"),
4157 keydb_get_resource_name (pub_hd));
4162 err = keydb_insert_keyblock (pub_hd, pub_root);
4164 log_error (_("error writing public keyring '%s': %s\n"),
4165 keydb_get_resource_name (pub_hd), gpg_strerror (err));
4168 keydb_release (pub_hd);
4175 no_enc_rsa = ((get_parameter_algo (para, pKEYTYPE, NULL)
4177 && get_parameter_uint (para, pKEYUSAGE)
4178 && !((get_parameter_uint (para, pKEYUSAGE)
4179 & PUBKEY_USAGE_ENC)) );
4181 pk = find_kbnode (pub_root, PKT_PUBLIC_KEY)->pkt->pkt.public_key;
4183 keyid_from_pk (pk, pk->main_keyid);
4184 register_trusted_keyid (pk->main_keyid);
4186 update_ownertrust (pk, ((get_ownertrust (pk) & ~TRUST_MASK)
4187 | TRUST_ULTIMATE ));
4189 gen_standard_revoke (pk, cache_nonce);
4193 tty_printf (_("public and secret key created and signed.\n") );
4195 list_keyblock_direct (pub_root, 0, 1, 1);
4200 && (get_parameter_algo (para, pKEYTYPE, NULL) == PUBKEY_ALGO_DSA
4202 && !get_parameter (para, pSUBKEYTYPE) )
4204 tty_printf(_("Note that this key cannot be used for "
4205 "encryption. You may want to use\n"
4206 "the command \"--edit-key\" to generate a "
4207 "subkey for this purpose.\n") );
4215 log_error ("key generation failed: %s\n", gpg_strerror (err) );
4217 tty_printf (_("Key generation failed: %s\n"), gpg_strerror (err) );
4218 write_status_error (card? "card_key_generate":"key_generate", err);
4219 print_status_key_not_created ( get_parameter_value (para, pHANDLE) );
4223 PKT_public_key *pk = find_kbnode (pub_root,
4224 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
4225 print_status_key_created (did_sub? 'B':'P', pk,
4226 get_parameter_value (para, pHANDLE));
4229 release_kbnode (pub_root);
4230 xfree (cache_nonce);
4234 /* Add a new subkey to an existing key. Returns 0 if a new key has
4235 been generated and put into the keyblocks. */
4237 generate_subkeypair (ctrl_t ctrl, kbnode_t keyblock)
4239 gpg_error_t err = 0;
4241 PKT_public_key *pri_psk = NULL;
4242 PKT_public_key *sub_psk = NULL;
4246 unsigned int nbits = 0;
4249 char *hexgrip = NULL;
4250 char *serialno = NULL;
4252 /* Break out the primary key. */
4253 node = find_kbnode (keyblock, PKT_PUBLIC_KEY);
4256 log_error ("Oops; primary key missing in keyblock!\n");
4257 err = gpg_error (GPG_ERR_BUG);
4260 pri_psk = node->pkt->pkt.public_key;
4262 cur_time = make_timestamp ();
4264 if (pri_psk->timestamp > cur_time)
4266 ulong d = pri_psk->timestamp - cur_time;
4267 log_info ( d==1 ? _("key has been created %lu second "
4268 "in future (time warp or clock problem)\n")
4269 : _("key has been created %lu seconds "
4270 "in future (time warp or clock problem)\n"), d );
4271 if (!opt.ignore_time_conflict)
4273 err = gpg_error (GPG_ERR_TIME_CONFLICT);
4278 if (pri_psk->version < 4)
4280 log_info (_("Note: creating subkeys for v3 keys "
4281 "is not OpenPGP compliant\n"));
4282 err = gpg_error (GPG_ERR_CONFLICT);
4286 err = hexkeygrip_from_pk (pri_psk, &hexgrip);
4289 if (agent_get_keyinfo (NULL, hexgrip, &serialno))
4291 tty_printf (_("Secret parts of primary key are not available.\n"));
4295 tty_printf (_("Secret parts of primary key are stored on-card.\n"));
4299 algo = ask_algo (ctrl, 1, NULL, &use, &hexgrip);
4304 else if (algo == PUBKEY_ALGO_ECDSA
4305 || algo == PUBKEY_ALGO_EDDSA
4306 || algo == PUBKEY_ALGO_ECDH)
4307 curve = ask_curve (&algo, NULL);
4309 nbits = ask_keysize (algo, 0);
4311 expire = ask_expire_interval (0, NULL);
4312 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
4313 _("Really create? (y/N) ")))
4315 err = gpg_error (GPG_ERR_CANCELED);
4320 err = do_create_from_keygrip (ctrl, algo, hexgrip,
4321 keyblock, cur_time, expire, 1);
4323 err = do_create (algo, nbits, curve,
4324 keyblock, cur_time, expire, 1, 0, NULL, NULL);
4328 /* Get the pointer to the generated public subkey packet. */
4329 for (node = keyblock; node; node = node->next)
4330 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4331 sub_psk = node->pkt->pkt.public_key;
4333 /* Write the binding signature. */
4334 err = write_keybinding (keyblock, pri_psk, sub_psk, use, cur_time, NULL);
4338 write_status_text (STATUS_KEY_CREATED, "S");
4345 log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
4350 #ifdef ENABLE_CARD_SUPPORT
4351 /* Generate a subkey on a card. */
4353 generate_card_subkeypair (kbnode_t pub_keyblock,
4354 int keyno, const char *serialno)
4356 gpg_error_t err = 0;
4358 PKT_public_key *pri_pk = NULL;
4363 struct para_data_s *para = NULL;
4365 assert (keyno >= 1 && keyno <= 3);
4367 para = xtrycalloc (1, sizeof *para + strlen (serialno) );
4370 err = gpg_error_from_syserror ();
4373 para->key = pSERIALNO;
4374 strcpy (para->u.value, serialno);
4376 /* Break out the primary secret key */
4377 node = find_kbnode (pub_keyblock, PKT_PUBLIC_KEY);
4380 log_error ("Oops; publkic key lost!\n");
4381 err = gpg_error (GPG_ERR_INTERNAL);
4384 pri_pk = node->pkt->pkt.public_key;
4386 cur_time = make_timestamp();
4387 if (pri_pk->timestamp > cur_time)
4389 ulong d = pri_pk->timestamp - cur_time;
4390 log_info (d==1 ? _("key has been created %lu second "
4391 "in future (time warp or clock problem)\n")
4392 : _("key has been created %lu seconds "
4393 "in future (time warp or clock problem)\n"), d );
4394 if (!opt.ignore_time_conflict)
4396 err = gpg_error (GPG_ERR_TIME_CONFLICT);
4401 if (pri_pk->version < 4)
4403 log_info (_("Note: creating subkeys for v3 keys "
4404 "is not OpenPGP compliant\n"));
4405 err = gpg_error (GPG_ERR_NOT_SUPPORTED);
4409 algo = PUBKEY_ALGO_RSA;
4410 expire = ask_expire_interval (0, NULL);
4412 use = PUBKEY_USAGE_SIG;
4413 else if (keyno == 2)
4414 use = PUBKEY_USAGE_ENC;
4416 use = PUBKEY_USAGE_AUTH;
4417 if (!cpr_enabled() && !cpr_get_answer_is_yes("keygen.cardsub.okay",
4418 _("Really create? (y/N) ")))
4420 err = gpg_error (GPG_ERR_CANCELED);
4424 /* Note, that depending on the backend, the card key generation may
4426 err = gen_card_key (algo, keyno, 0, pub_keyblock, &cur_time, expire);
4427 /* Get the pointer to the generated public subkey packet. */
4430 PKT_public_key *sub_pk = NULL;
4432 for (node = pub_keyblock; node; node = node->next)
4433 if (node->pkt->pkttype == PKT_PUBLIC_SUBKEY)
4434 sub_pk = node->pkt->pkt.public_key;
4436 err = write_keybinding (pub_keyblock, pri_pk, sub_pk,
4437 use, cur_time, NULL);
4442 log_error (_("Key generation failed: %s\n"), gpg_strerror (err) );
4444 write_status_text (STATUS_KEY_CREATED, "S");
4445 release_parameter_list (para);
4448 #endif /* !ENABLE_CARD_SUPPORT */
4451 * Write a keyblock to an output stream
4454 write_keyblock( IOBUF out, KBNODE node )
4456 for( ; node ; node = node->next )
4458 if(!is_deleted_kbnode(node))
4460 int rc = build_packet( out, node->pkt );
4463 log_error("build_packet(%d) failed: %s\n",
4464 node->pkt->pkttype, gpg_strerror (rc) );
4474 /* Note that timestamp is an in/out arg. */
4476 gen_card_key (int algo, int keyno, int is_primary, kbnode_t pub_root,
4477 u32 *timestamp, u32 expireval)
4479 #ifdef ENABLE_CARD_SUPPORT
4481 struct agent_card_genkey_s info;
4485 if (algo != PUBKEY_ALGO_RSA)
4486 return gpg_error (GPG_ERR_PUBKEY_ALGO);
4488 pk = xtrycalloc (1, sizeof *pk );
4490 return gpg_error_from_syserror ();
4491 pkt = xtrycalloc (1, sizeof *pkt);
4495 return gpg_error_from_syserror ();
4498 /* Note: SCD knows the serialnumber, thus there is no point in passing it. */
4499 err = agent_scd_genkey (&info, keyno, 1, NULL, *timestamp);
4500 /* The code below is not used because we force creation of
4501 * the a card key (3rd arg).
4502 * if (gpg_err_code (rc) == GPG_ERR_EEXIST)
4504 * tty_printf ("\n");
4505 * log_error ("WARNING: key does already exists!\n");
4506 * tty_printf ("\n");
4507 * if ( cpr_get_answer_is_yes( "keygen.card.replace_key",
4508 * _("Replace existing key? ")))
4509 * rc = agent_scd_genkey (&info, keyno, 1);
4512 if (!err && (!info.n || !info.e))
4514 log_error ("communication error with SCD\n");
4515 gcry_mpi_release (info.n);
4516 gcry_mpi_release (info.e);
4517 err = gpg_error (GPG_ERR_GENERAL);
4521 log_error ("key generation failed: %s\n", gpg_strerror (err));
4527 /* Send the learn command so that the agent creates a shadow key for
4528 card key. We need to do that now so that we are able to create
4529 the self-signatures. */
4530 err = agent_scd_learn (NULL, 0);
4533 /* Oops: Card removed during generation. */
4534 log_error (_("OpenPGP card not available: %s\n"), gpg_strerror (err));
4540 if (*timestamp != info.created_at)
4541 log_info ("NOTE: the key does not use the suggested creation date\n");
4542 *timestamp = info.created_at;
4544 pk->timestamp = info.created_at;
4547 pk->expiredate = pk->timestamp + expireval;
4548 pk->pubkey_algo = algo;
4549 pk->pkey[0] = info.n;
4550 pk->pkey[1] = info.e;
4552 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
4553 pkt->pkt.public_key = pk;
4554 add_kbnode (pub_root, new_kbnode (pkt));
4564 return gpg_error (GPG_ERR_NOT_SUPPORTED);
4565 #endif /*!ENABLE_CARD_SUPPORT*/
4571 gen_card_key_with_backup (int algo, int keyno, int is_primary,
4572 KBNODE pub_root, u32 timestamp,
4573 u32 expireval, struct para_data_s *para)
4575 #if ENABLE_CARD_SUPPORT && 0
4576 /* FIXME: Move this to gpg-agent. */
4580 PKT_secret_key *sk, *sk_unprotected = NULL, *sk_protected = NULL;
4586 /* Get the size of the key directly from the card. */
4588 struct agent_card_info_s info;
4590 memset (&info, 0, sizeof info);
4591 if (!agent_scd_getattr ("KEY-ATTR", &info)
4592 && info.key_attr[1].algo)
4593 nbits = info.key_attr[1].nbits;
4595 nbits = 1024; /* All pre-v2.0 cards. */
4596 agent_release_card_info (&info);
4599 /* Create a key of this size in memory. */
4600 rc = generate_raw_key (algo, nbits, timestamp,
4601 &sk_unprotected, &sk_protected);
4605 /* Store the key to the card. */
4606 rc = save_unprotected_key_to_card (sk_unprotected, keyno);
4609 log_error (_("storing key onto card failed: %s\n"), gpg_strerror (rc));
4610 free_secret_key (sk_unprotected);
4611 free_secret_key (sk_protected);
4612 write_status_errcode ("save_key_to_card", rc);
4616 /* Get rid of the secret key parameters and store the serial numer. */
4617 sk = sk_unprotected;
4618 n = pubkey_get_nskey (sk->pubkey_algo);
4619 for (i=pubkey_get_npkey (sk->pubkey_algo); i < n; i++)
4621 gcry_mpi_release (sk->skey[i]);
4624 i = pubkey_get_npkey (sk->pubkey_algo);
4625 sk->skey[i] = gcry_mpi_set_opaque (NULL, xstrdup ("dummydata"), 10*8);
4626 sk->is_protected = 1;
4627 sk->protect.s2k.mode = 1002;
4628 s = get_parameter_value (para, pSERIALNO);
4630 for (sk->protect.ivlen=0; sk->protect.ivlen < 16 && *s && s[1];
4631 sk->protect.ivlen++, s += 2)
4632 sk->protect.iv[sk->protect.ivlen] = xtoi_2 (s);
4634 /* Now write the *protected* secret key to the file. */
4636 char name_buffer[50];
4641 keyid_from_sk (sk, NULL);
4642 snprintf (name_buffer, sizeof name_buffer, "sk_%08lX%08lX.gpg",
4643 (ulong)sk->keyid[0], (ulong)sk->keyid[1]);
4645 fname = make_filename (backup_dir, name_buffer, NULL);
4646 /* Note that the umask call is not anymore needed because
4647 iobuf_create now takes care of it. However, it does not harm
4648 and thus we keep it. */
4649 oldmask = umask (077);
4650 if (is_secured_filename (fname))
4653 gpg_err_set_errno (EPERM);
4656 fp = iobuf_create (fname, 1);
4660 rc = gpg_error_from_syserror ();
4661 log_error (_("can't create backup file '%s': %s\n"),
4662 fname, strerror(errno) );
4664 free_secret_key (sk_unprotected);
4665 free_secret_key (sk_protected);
4669 pkt = xcalloc (1, sizeof *pkt);
4670 pkt->pkttype = PKT_SECRET_KEY;
4671 pkt->pkt.secret_key = sk_protected;
4672 sk_protected = NULL;
4674 rc = build_packet (fp, pkt);
4677 log_error("build packet failed: %s\n", gpg_strerror (rc));
4682 unsigned char array[MAX_FINGERPRINT_LEN];
4686 iobuf_ioctl (NULL, IOBUF_IOCTL_INVALIDATE_CACHE, 0, (char*)fname);
4687 log_info (_("Note: backup of card key saved to '%s'\n"), fname);
4689 fingerprint_from_sk (sk, array, &n);
4690 p = fprbuf = xmalloc (MAX_FINGERPRINT_LEN*2 + 1 + 1);
4691 for (i=0; i < n ; i++, p += 2)
4692 sprintf (p, "%02X", array[i]);
4696 write_status_text_and_buffer (STATUS_BACKUP_KEY_CREATED,
4698 fname, strlen (fname),
4707 free_secret_key (sk_unprotected);
4712 /* Create the public key from the secret key. */
4713 pk = xcalloc (1, sizeof *pk );
4714 pk->timestamp = sk->timestamp;
4715 pk->version = sk->version;
4717 pk->expiredate = sk->expiredate = sk->timestamp + expireval;
4718 pk->pubkey_algo = sk->pubkey_algo;
4719 n = pubkey_get_npkey (sk->pubkey_algo);
4720 for (i=0; i < n; i++)
4721 pk->pkey[i] = mpi_copy (sk->skey[i]);
4723 /* Build packets and add them to the node lists. */
4724 pkt = xcalloc (1,sizeof *pkt);
4725 pkt->pkttype = is_primary ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
4726 pkt->pkt.public_key = pk;
4727 add_kbnode(pub_root, new_kbnode( pkt ));
4729 pkt = xcalloc (1,sizeof *pkt);
4730 pkt->pkttype = is_primary ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
4731 pkt->pkt.secret_key = sk;
4732 add_kbnode(sec_root, new_kbnode( pkt ));
4736 # if __GCC__ && ENABLE_CARD_SUPPORT
4737 # warning Card support still missing
4746 return gpg_error (GPG_ERR_NOT_SUPPORTED);
4747 #endif /*!ENABLE_CARD_SUPPORT*/
4753 save_unprotected_key_to_card (PKT_public_key *sk, int keyno)
4756 unsigned char *rsa_n = NULL;
4757 unsigned char *rsa_e = NULL;
4758 unsigned char *rsa_p = NULL;
4759 unsigned char *rsa_q = NULL;
4760 size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
4761 unsigned char *sexp = NULL;
4763 char numbuf[55], numbuf2[50];
4765 assert (is_RSA (sk->pubkey_algo));
4766 assert (!sk->is_protected);
4768 /* Copy the parameters into straight buffers. */
4769 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_n, &rsa_n_len, sk->skey[0]);
4770 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_e, &rsa_e_len, sk->skey[1]);
4771 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_p, &rsa_p_len, sk->skey[3]);
4772 gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_q, &rsa_q_len, sk->skey[4]);
4773 if (!rsa_n || !rsa_e || !rsa_p || !rsa_q)
4775 rc = GPG_ERR_INV_ARG;
4779 /* Put the key into an S-expression. */
4780 sexp = p = xmalloc_secure (30
4781 + rsa_n_len + rsa_e_len + rsa_p_len + rsa_q_len
4782 + 4*sizeof (numbuf) + 25 + sizeof(numbuf) + 20);
4784 p = stpcpy (p,"(11:private-key(3:rsa(1:n");
4785 sprintf (numbuf, "%u:", (unsigned int)rsa_n_len);
4786 p = stpcpy (p, numbuf);
4787 memcpy (p, rsa_n, rsa_n_len);
4790 sprintf (numbuf, ")(1:e%u:", (unsigned int)rsa_e_len);
4791 p = stpcpy (p, numbuf);
4792 memcpy (p, rsa_e, rsa_e_len);
4795 sprintf (numbuf, ")(1:p%u:", (unsigned int)rsa_p_len);
4796 p = stpcpy (p, numbuf);
4797 memcpy (p, rsa_p, rsa_p_len);
4800 sprintf (numbuf, ")(1:q%u:", (unsigned int)rsa_q_len);
4801 p = stpcpy (p, numbuf);
4802 memcpy (p, rsa_q, rsa_q_len);
4805 p = stpcpy (p,"))(10:created-at");
4806 sprintf (numbuf2, "%lu", (unsigned long)sk->timestamp);
4807 sprintf (numbuf, "%lu:", (unsigned long)strlen (numbuf2));
4808 p = stpcpy (stpcpy (stpcpy (p, numbuf), numbuf2), "))");
4810 /* Fixme: Unfortunately we don't have the serialnumber available -
4811 thus we can't pass it down to the agent. */
4812 rc = agent_scd_writekey (keyno, NULL, sexp, p - sexp);
4822 #endif /*ENABLE_CARD_SUPPORT*/