1 /* keygen.c - generate a key pair
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
56 pKEYEXPIRE, /* in n seconds */
57 pSUBKEYEXPIRE, /* in n seconds */
64 struct para_data_s *next;
72 struct revocation_key revkey;
77 struct output_control_s {
85 armor_filter_context_t afx;
91 armor_filter_context_t afx;
96 struct opaque_data_usage_and_pk {
102 static int prefs_initialized = 0;
103 static byte sym_prefs[MAX_PREFS];
104 static int nsym_prefs;
105 static byte hash_prefs[MAX_PREFS];
106 static int nhash_prefs;
107 static byte zip_prefs[MAX_PREFS];
108 static int nzip_prefs;
109 static int mdc_available;
111 static void do_generate_keypair( struct para_data_s *para,
112 struct output_control_s *outctrl );
113 static int write_keyblock( IOBUF out, KBNODE node );
117 write_uid( KBNODE root, const char *s )
119 PACKET *pkt = m_alloc_clear(sizeof *pkt );
120 size_t n = strlen(s);
122 pkt->pkttype = PKT_USER_ID;
123 pkt->pkt.user_id = m_alloc_clear( sizeof *pkt->pkt.user_id + n - 1 );
124 pkt->pkt.user_id->len = n;
125 pkt->pkt.user_id->ref = 1;
126 strcpy(pkt->pkt.user_id->name, s);
127 add_kbnode( root, new_kbnode( pkt ) );
131 do_add_key_flags (PKT_signature *sig, unsigned int use)
139 if (use & PUBKEY_USAGE_SIG)
140 buf[0] |= 0x01 | 0x02;
141 if (use & PUBKEY_USAGE_ENC)
142 buf[0] |= 0x04 | 0x08;
143 build_sig_subpkt (sig, SIGSUBPKT_KEY_FLAGS, buf, 1);
148 keygen_add_key_expire( PKT_signature *sig, void *opaque )
150 PKT_public_key *pk = opaque;
154 if( pk->expiredate ) {
155 if(pk->expiredate > pk->timestamp)
156 u= pk->expiredate - pk->timestamp;
160 buf[0] = (u >> 24) & 0xff;
161 buf[1] = (u >> 16) & 0xff;
162 buf[2] = (u >> 8) & 0xff;
164 build_sig_subpkt( sig, SIGSUBPKT_KEY_EXPIRE, buf, 4 );
168 /* Make sure we don't leave a key expiration subpacket lying
170 delete_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE);
177 keygen_add_key_flags_and_expire (PKT_signature *sig, void *opaque)
179 struct opaque_data_usage_and_pk *oduap = opaque;
181 do_add_key_flags (sig, oduap->usage);
182 return keygen_add_key_expire (sig, oduap->pk);
186 set_one_pref (int val, int type, const char *item, byte *buf, int *nbuf)
190 for (i=0; i < *nbuf; i++ )
193 log_info (_("preference `%s' duplicated\n"), item);
197 if (*nbuf >= MAX_PREFS)
200 log_info(_("too many cipher preferences\n"));
202 log_info(_("too many digest preferences\n"));
204 log_info(_("too many compression preferences\n"));
211 buf[(*nbuf)++] = val;
216 * Parse the supplied string and use it to set the standard
217 * preferences. The string may be in a form like the one printed by
218 * "pref" (something like: "S10 S3 H3 H2 Z2 Z1") or the actual
219 * cipher/hash/compress names. Use NULL to set the default
220 * preferences. Returns: 0 = okay
223 keygen_set_std_prefs (const char *string,int personal)
225 byte sym[MAX_PREFS], hash[MAX_PREFS], zip[MAX_PREFS];
226 int nsym=0, nhash=0, nzip=0, mdc=1; /* mdc defaults on */
229 if (!string || !ascii_strcasecmp (string, "default")) {
230 if (opt.def_preference_list)
231 string=opt.def_preference_list;
232 else if ( !check_cipher_algo(CIPHER_ALGO_IDEA) )
233 string = "S7 S3 S2 S1 H2 H3 Z2 Z1";
235 string = "S7 S3 S2 H2 H3 Z2 Z1";
237 /* If we have it, IDEA goes *after* 3DES so it won't be used
238 unless we're encrypting along with a V3 key. Ideally, we
239 would only put the S1 preference in if the key was RSA and
240 <=2048 bits, as that is what won't break PGP2, but that is
241 difficult with the current code, and not really worth
242 checking as a non-RSA <=2048 bit key wouldn't be usable by
245 else if (!ascii_strcasecmp (string, "none"))
250 char *tok,*prefstring;
252 prefstring=m_strdup(string); /* need a writable string! */
254 while((tok=strsep(&prefstring," ,")))
256 if((val=string_to_cipher_algo(tok)))
258 if(set_one_pref(val,1,tok,sym,&nsym))
261 else if((val=string_to_digest_algo(tok)))
263 if(set_one_pref(val,2,tok,hash,&nhash))
266 else if((val=string_to_compress_algo(tok))>-1)
268 if(set_one_pref(val,3,tok,zip,&nzip))
271 else if (ascii_strcasecmp(tok,"mdc")==0)
273 else if (ascii_strcasecmp(tok,"no-mdc")==0)
277 log_info (_("invalid item `%s' in preference string\n"),tok);
289 if(personal==PREFTYPE_SYM)
291 m_free(opt.personal_cipher_prefs);
294 opt.personal_cipher_prefs=NULL;
299 opt.personal_cipher_prefs=
300 m_alloc(sizeof(prefitem_t *)*(nsym+1));
302 for (i=0; i<nsym; i++)
304 opt.personal_cipher_prefs[i].type = PREFTYPE_SYM;
305 opt.personal_cipher_prefs[i].value = sym[i];
308 opt.personal_cipher_prefs[i].type = PREFTYPE_NONE;
309 opt.personal_cipher_prefs[i].value = 0;
312 else if(personal==PREFTYPE_HASH)
314 m_free(opt.personal_digest_prefs);
317 opt.personal_digest_prefs=NULL;
322 opt.personal_digest_prefs=
323 m_alloc(sizeof(prefitem_t *)*(nhash+1));
325 for (i=0; i<nhash; i++)
327 opt.personal_digest_prefs[i].type = PREFTYPE_HASH;
328 opt.personal_digest_prefs[i].value = hash[i];
331 opt.personal_digest_prefs[i].type = PREFTYPE_NONE;
332 opt.personal_digest_prefs[i].value = 0;
335 else if(personal==PREFTYPE_ZIP)
337 m_free(opt.personal_compress_prefs);
340 opt.personal_compress_prefs=NULL;
345 opt.personal_compress_prefs=
346 m_alloc(sizeof(prefitem_t *)*(nzip+1));
348 for (i=0; i<nzip; i++)
350 opt.personal_compress_prefs[i].type = PREFTYPE_ZIP;
351 opt.personal_compress_prefs[i].value = zip[i];
354 opt.personal_compress_prefs[i].type = PREFTYPE_NONE;
355 opt.personal_compress_prefs[i].value = 0;
361 memcpy (sym_prefs, sym, (nsym_prefs=nsym));
362 memcpy (hash_prefs, hash, (nhash_prefs=nhash));
363 memcpy (zip_prefs, zip, (nzip_prefs=nzip));
365 prefs_initialized = 1;
372 /* Return a fake user ID containing the preferences. Caller must
374 PKT_user_id *keygen_get_std_prefs(void)
377 PKT_user_id *uid=m_alloc_clear(sizeof(PKT_user_id));
379 if(!prefs_initialized)
380 keygen_set_std_prefs(NULL,0);
382 uid->prefs=m_alloc((sizeof(prefitem_t *)*
383 (nsym_prefs+nhash_prefs+nzip_prefs+1)));
385 for(i=0;i<nsym_prefs;i++,j++)
387 uid->prefs[j].type=PREFTYPE_SYM;
388 uid->prefs[j].value=sym_prefs[i];
391 for(i=0;i<nhash_prefs;i++,j++)
393 uid->prefs[j].type=PREFTYPE_HASH;
394 uid->prefs[j].value=hash_prefs[i];
397 for(i=0;i<nzip_prefs;i++,j++)
399 uid->prefs[j].type=PREFTYPE_ZIP;
400 uid->prefs[j].value=zip_prefs[i];
403 uid->prefs[j].type=PREFTYPE_NONE;
404 uid->prefs[j].value=0;
406 uid->mdc_feature=mdc_available;
412 add_feature_mdc (PKT_signature *sig,int enabled)
419 s = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n );
420 /* Already set or cleared */
422 ((enabled && (s[0] & 0x01)) || (!enabled && !(s[0] & 0x01))))
425 if (!s || !n) { /* create a new one */
427 buf = m_alloc_clear (n);
435 buf[0] |= 0x01; /* MDC feature */
439 /* Are there any bits set? */
445 delete_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES);
447 build_sig_subpkt (sig, SIGSUBPKT_FEATURES, buf, n);
453 keygen_upd_std_prefs( PKT_signature *sig, void *opaque )
455 if (!prefs_initialized)
456 keygen_set_std_prefs (NULL, 0);
459 build_sig_subpkt (sig, SIGSUBPKT_PREF_SYM, sym_prefs, nsym_prefs);
462 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_SYM);
463 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_SYM);
467 build_sig_subpkt (sig, SIGSUBPKT_PREF_HASH, hash_prefs, nhash_prefs);
470 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_HASH);
471 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_HASH);
475 build_sig_subpkt (sig, SIGSUBPKT_PREF_COMPR, zip_prefs, nzip_prefs);
478 delete_sig_subpkt (sig->hashed, SIGSUBPKT_PREF_COMPR);
479 delete_sig_subpkt (sig->unhashed, SIGSUBPKT_PREF_COMPR);
482 /* Make sure that the MDC feature flag is set if needed */
483 add_feature_mdc (sig,mdc_available);
490 * Add preference to the self signature packet.
491 * This is only called for packets with version > 3.
495 keygen_add_std_prefs( PKT_signature *sig, void *opaque )
497 PKT_public_key *pk = opaque;
500 do_add_key_flags (sig, pk->pubkey_usage);
501 keygen_add_key_expire( sig, opaque );
502 keygen_upd_std_prefs (sig, opaque);
504 buf[0] = 0x80; /* no modify - It is reasonable that a key holder
505 * has the possibility to reject signatures from users
506 * who are known to sign everything without any
507 * validation - so a signed key should be send
508 * to the holder who in turn can put it on a keyserver
510 build_sig_subpkt( sig, SIGSUBPKT_KS_FLAGS, buf, 1 );
516 keygen_add_revkey(PKT_signature *sig, void *opaque)
518 struct revocation_key *revkey=opaque;
519 byte buf[2+MAX_FINGERPRINT_LEN];
521 buf[0]=revkey->class;
522 buf[1]=revkey->algid;
523 memcpy(&buf[2],revkey->fpr,MAX_FINGERPRINT_LEN);
525 build_sig_subpkt(sig,SIGSUBPKT_REV_KEY,buf,2+MAX_FINGERPRINT_LEN);
527 /* All sigs with revocation keys set are nonrevocable */
528 sig->flags.revocable=0;
530 build_sig_subpkt( sig, SIGSUBPKT_REVOCABLE, buf, 1 );
538 write_direct_sig( KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
539 struct revocation_key *revkey )
548 log_info(_("writing direct signature\n"));
550 /* get the pk packet from the pub_tree */
551 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
554 pk = node->pkt->pkt.public_key;
556 /* we have to cache the key, so that the verification of the signature
557 * creation is able to retrieve the public key */
558 cache_public_key (pk);
560 /* and make the signature */
561 rc = make_keysig_packet(&sig,pk,NULL,NULL,sk,0x1F,0,0,0,0,
562 keygen_add_revkey,revkey);
564 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
568 pkt = m_alloc_clear( sizeof *pkt );
569 pkt->pkttype = PKT_SIGNATURE;
570 pkt->pkt.signature = sig;
571 add_kbnode( root, new_kbnode( pkt ) );
576 write_selfsig( KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
587 log_info(_("writing self signature\n"));
589 /* get the uid packet from the list */
590 node = find_kbnode( root, PKT_USER_ID );
592 BUG(); /* no user id packet in tree */
593 uid = node->pkt->pkt.user_id;
594 /* get the pk packet from the pub_tree */
595 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
598 pk = node->pkt->pkt.public_key;
599 pk->pubkey_usage = use;
600 /* we have to cache the key, so that the verification of the signature
601 * creation is able to retrieve the public key */
602 cache_public_key (pk);
604 /* and make the signature */
605 rc = make_keysig_packet( &sig, pk, uid, NULL, sk, 0x13, 0, 0, 0, 0,
606 keygen_add_std_prefs, pk );
608 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
612 pkt = m_alloc_clear( sizeof *pkt );
613 pkt->pkttype = PKT_SIGNATURE;
614 pkt->pkt.signature = sig;
615 add_kbnode( root, new_kbnode( pkt ) );
620 write_keybinding( KBNODE root, KBNODE pub_root, PKT_secret_key *sk,
627 PKT_public_key *pk, *subpk;
628 struct opaque_data_usage_and_pk oduap;
631 log_info(_("writing key binding signature\n"));
633 /* get the pk packet from the pub_tree */
634 node = find_kbnode( pub_root, PKT_PUBLIC_KEY );
637 pk = node->pkt->pkt.public_key;
638 /* we have to cache the key, so that the verification of the signature
639 * creation is able to retrieve the public key */
640 cache_public_key (pk);
642 /* find the last subkey */
644 for(node=pub_root; node; node = node->next ) {
645 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
646 subpk = node->pkt->pkt.public_key;
651 /* and make the signature */
654 rc = make_keysig_packet( &sig, pk, NULL, subpk, sk, 0x18, 0, 0, 0, 0,
655 keygen_add_key_flags_and_expire, &oduap );
657 log_error("make_keysig_packet failed: %s\n", g10_errstr(rc) );
661 pkt = m_alloc_clear( sizeof *pkt );
662 pkt->pkttype = PKT_SIGNATURE;
663 pkt->pkt.signature = sig;
664 add_kbnode( root, new_kbnode( pkt ) );
670 gen_elg(int algo, unsigned nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
671 STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval )
681 assert( is_ELGAMAL(algo) );
685 log_info(_("keysize invalid; using %u bits\n"), nbits );
689 nbits = ((nbits + 31) / 32) * 32;
690 log_info(_("keysize rounded up to %u bits\n"), nbits );
693 rc = pubkey_generate( algo, nbits, skey, &factors );
695 log_error("pubkey_generate failed: %s\n", g10_errstr(rc) );
699 sk = m_alloc_clear( sizeof *sk );
700 pk = m_alloc_clear( sizeof *pk );
701 sk->timestamp = pk->timestamp = make_timestamp();
702 sk->version = pk->version = 4;
704 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
706 sk->pubkey_algo = pk->pubkey_algo = algo;
707 pk->pkey[0] = mpi_copy( skey[0] );
708 pk->pkey[1] = mpi_copy( skey[1] );
709 pk->pkey[2] = mpi_copy( skey[2] );
710 sk->skey[0] = skey[0];
711 sk->skey[1] = skey[1];
712 sk->skey[2] = skey[2];
713 sk->skey[3] = skey[3];
714 sk->is_protected = 0;
715 sk->protect.algo = 0;
717 sk->csum = checksum_mpi( sk->skey[3] );
718 if( ret_sk ) /* not a subkey: return an unprotected version of the sk */
719 *ret_sk = copy_secret_key( NULL, sk );
722 sk->protect.algo = dek->algo;
723 sk->protect.s2k = *s2k;
724 rc = protect_secret_key( sk, dek );
726 log_error("protect_secret_key failed: %s\n", g10_errstr(rc) );
733 pkt = m_alloc_clear(sizeof *pkt);
734 pkt->pkttype = ret_sk ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
735 pkt->pkt.public_key = pk;
736 add_kbnode(pub_root, new_kbnode( pkt ));
738 /* don't know whether it makes sense to have the factors, so for now
739 * we store them in the secret keyring (but they are not secret) */
740 pkt = m_alloc_clear(sizeof *pkt);
741 pkt->pkttype = ret_sk ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
742 pkt->pkt.secret_key = sk;
743 add_kbnode(sec_root, new_kbnode( pkt ));
744 for(i=0; factors[i]; i++ )
745 add_kbnode( sec_root,
746 make_mpi_comment_node("#:ELG_factor:", factors[i] ));
756 gen_dsa(unsigned int nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
757 STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval )
767 if( nbits > 1024 || nbits < 512 ) {
769 log_info(_("keysize invalid; using %u bits\n"), nbits );
773 nbits = ((nbits + 63) / 64) * 64;
774 log_info(_("keysize rounded up to %u bits\n"), nbits );
777 rc = pubkey_generate( PUBKEY_ALGO_DSA, nbits, skey, &factors );
779 log_error("pubkey_generate failed: %s\n", g10_errstr(rc) );
783 sk = m_alloc_clear( sizeof *sk );
784 pk = m_alloc_clear( sizeof *pk );
785 sk->timestamp = pk->timestamp = make_timestamp();
786 sk->version = pk->version = 4;
788 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
790 sk->pubkey_algo = pk->pubkey_algo = PUBKEY_ALGO_DSA;
791 pk->pkey[0] = mpi_copy( skey[0] );
792 pk->pkey[1] = mpi_copy( skey[1] );
793 pk->pkey[2] = mpi_copy( skey[2] );
794 pk->pkey[3] = mpi_copy( skey[3] );
795 sk->skey[0] = skey[0];
796 sk->skey[1] = skey[1];
797 sk->skey[2] = skey[2];
798 sk->skey[3] = skey[3];
799 sk->skey[4] = skey[4];
800 sk->is_protected = 0;
801 sk->protect.algo = 0;
803 sk->csum = checksum_mpi ( sk->skey[4] );
804 if( ret_sk ) /* not a subkey: return an unprotected version of the sk */
805 *ret_sk = copy_secret_key( NULL, sk );
808 sk->protect.algo = dek->algo;
809 sk->protect.s2k = *s2k;
810 rc = protect_secret_key( sk, dek );
812 log_error("protect_secret_key failed: %s\n", g10_errstr(rc) );
819 pkt = m_alloc_clear(sizeof *pkt);
820 pkt->pkttype = ret_sk ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
821 pkt->pkt.public_key = pk;
822 add_kbnode(pub_root, new_kbnode( pkt ));
824 /* don't know whether it makes sense to have the factors, so for now
825 * we store them in the secret keyring (but they are not secret)
826 * p = 2 * q * f1 * f2 * ... * fn
827 * We store only f1 to f_n-1; fn can be calculated because p and q
830 pkt = m_alloc_clear(sizeof *pkt);
831 pkt->pkttype = ret_sk ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
832 pkt->pkt.secret_key = sk;
833 add_kbnode(sec_root, new_kbnode( pkt ));
834 for(i=1; factors[i]; i++ ) /* the first one is q */
835 add_kbnode( sec_root,
836 make_mpi_comment_node("#:DSA_factor:", factors[i] ));
843 * Generate an RSA key.
846 gen_rsa(int algo, unsigned nbits, KBNODE pub_root, KBNODE sec_root, DEK *dek,
847 STRING2KEY *s2k, PKT_secret_key **ret_sk, u32 expireval )
856 assert( is_RSA(algo) );
860 log_info(_("keysize invalid; using %u bits\n"), nbits );
864 nbits = ((nbits + 31) / 32) * 32;
865 log_info(_("keysize rounded up to %u bits\n"), nbits );
868 rc = pubkey_generate( algo, nbits, skey, &factors );
870 log_error("pubkey_generate failed: %s\n", g10_errstr(rc) );
874 sk = m_alloc_clear( sizeof *sk );
875 pk = m_alloc_clear( sizeof *pk );
876 sk->timestamp = pk->timestamp = make_timestamp();
877 sk->version = pk->version = 4;
879 sk->expiredate = pk->expiredate = sk->timestamp + expireval;
881 sk->pubkey_algo = pk->pubkey_algo = algo;
882 pk->pkey[0] = mpi_copy( skey[0] );
883 pk->pkey[1] = mpi_copy( skey[1] );
884 sk->skey[0] = skey[0];
885 sk->skey[1] = skey[1];
886 sk->skey[2] = skey[2];
887 sk->skey[3] = skey[3];
888 sk->skey[4] = skey[4];
889 sk->skey[5] = skey[5];
890 sk->is_protected = 0;
891 sk->protect.algo = 0;
893 sk->csum = checksum_mpi (sk->skey[2] );
894 sk->csum += checksum_mpi (sk->skey[3] );
895 sk->csum += checksum_mpi (sk->skey[4] );
896 sk->csum += checksum_mpi (sk->skey[5] );
897 if( ret_sk ) /* not a subkey: return an unprotected version of the sk */
898 *ret_sk = copy_secret_key( NULL, sk );
901 sk->protect.algo = dek->algo;
902 sk->protect.s2k = *s2k;
903 rc = protect_secret_key( sk, dek );
905 log_error("protect_secret_key failed: %s\n", g10_errstr(rc) );
912 pkt = m_alloc_clear(sizeof *pkt);
913 pkt->pkttype = ret_sk ? PKT_PUBLIC_KEY : PKT_PUBLIC_SUBKEY;
914 pkt->pkt.public_key = pk;
915 add_kbnode(pub_root, new_kbnode( pkt ));
917 pkt = m_alloc_clear(sizeof *pkt);
918 pkt->pkttype = ret_sk ? PKT_SECRET_KEY : PKT_SECRET_SUBKEY;
919 pkt->pkt.secret_key = sk;
920 add_kbnode(sec_root, new_kbnode( pkt ));
928 * return 0 on error or the multiplier
931 check_valid_days( const char *s )
941 return 0; /* e.g. "2323wc" */
942 if( *s == 'd' || *s == 'D' )
944 if( *s == 'w' || *s == 'W' )
946 if( *s == 'm' || *s == 'M' )
948 if( *s == 'y' || *s == 'Y' )
955 * Returns: 0 to create both a DSA and a ElGamal key.
956 * and only if key flags are to be written the desired usage.
959 ask_algo (int addmode, unsigned int *r_usage)
965 tty_printf(_("Please select what kind of key you want:\n"));
967 tty_printf(_(" (%d) DSA and ElGamal (default)\n"), 1 );
968 tty_printf( _(" (%d) DSA (sign only)\n"), 2 );
970 tty_printf( _(" (%d) ElGamal (encrypt only)\n"), 3 );
972 tty_printf( _(" (%d) ElGamal (sign and encrypt)\n"), 4 );
973 tty_printf( _(" (%d) RSA (sign only)\n"), 5 );
975 tty_printf( _(" (%d) RSA (encrypt only)\n"), 6 );
977 tty_printf( _(" (%d) RSA (sign and encrypt)\n"), 7 );
980 answer = cpr_get("keygen.algo",_("Your selection? "));
982 algo = *answer? atoi(answer): 1;
984 if( algo == 1 && !addmode ) {
985 algo = 0; /* create both keys */
988 else if( algo == 7 && opt.expert ) {
989 algo = PUBKEY_ALGO_RSA;
990 *r_usage = PUBKEY_USAGE_ENC | PUBKEY_USAGE_SIG;
993 else if( algo == 6 && addmode ) {
994 algo = PUBKEY_ALGO_RSA;
995 *r_usage = PUBKEY_USAGE_ENC;
998 else if( algo == 5 ) {
999 algo = PUBKEY_ALGO_RSA;
1000 *r_usage = PUBKEY_USAGE_SIG;
1003 else if( algo == 4 && opt.expert)
1006 "The use of this algorithm is only supported by GnuPG. You will not be\n"
1007 "able to use this key to communicate with PGP users. This algorithm is also\n"
1008 "very slow, and may not be as secure as the other choices.\n"));
1010 if( cpr_get_answer_is_yes("keygen.algo.elg_se",
1011 _("Create anyway? ")))
1013 algo = PUBKEY_ALGO_ELGAMAL;
1017 else if( algo == 3 && addmode ) {
1018 algo = PUBKEY_ALGO_ELGAMAL_E;
1021 else if( algo == 2 ) {
1022 algo = PUBKEY_ALGO_DSA;
1026 tty_printf(_("Invalid selection.\n"));
1033 ask_keysize( int algo )
1038 if (algo != PUBKEY_ALGO_DSA && algo != PUBKEY_ALGO_RSA) {
1039 tty_printf (_("About to generate a new %s keypair.\n"
1040 " minimum keysize is 768 bits\n"
1041 " default keysize is 1024 bits\n"
1042 " highest suggested keysize is 2048 bits\n"),
1043 pubkey_algo_to_string(algo) );
1047 answer = cpr_get("keygen.size",
1048 _("What keysize do you want? (1024) "));
1050 nbits = *answer? atoi(answer): 1024;
1052 if( algo == PUBKEY_ALGO_DSA && (nbits < 512 || nbits > 1024) )
1053 tty_printf(_("DSA only allows keysizes from 512 to 1024\n"));
1054 else if( algo == PUBKEY_ALGO_RSA && nbits < 1024 )
1055 tty_printf(_("keysize too small;"
1056 " 1024 is smallest value allowed for RSA.\n"));
1057 else if( nbits < 768 )
1058 tty_printf(_("keysize too small;"
1059 " 768 is smallest value allowed.\n"));
1060 else if( nbits > 4096 ) {
1061 /* It is ridiculous and an annoyance to use larger key sizes!
1062 * GnuPG can handle much larger sizes; but it takes an eternity
1063 * to create such a key (but less than the time the Sirius
1064 * Computer Corporation needs to process one of the usual
1065 * complaints) and {de,en}cryption although needs some time.
1066 * So, before you complain about this limitation, I suggest that
1067 * you start a discussion with Marvin about this theme and then
1068 * do whatever you want. */
1069 tty_printf(_("keysize too large; %d is largest value allowed.\n"),
1072 else if( nbits > 2048 && !cpr_enabled() ) {
1074 _("Keysizes larger than 2048 are not suggested because\n"
1075 "computations take REALLY long!\n"));
1076 if( cpr_get_answer_is_yes("keygen.size.huge.okay",_(
1077 "Are you sure that you want this keysize? ")) ) {
1078 tty_printf(_("Okay, but keep in mind that your monitor "
1079 "and keyboard radiation is also very vulnerable "
1087 tty_printf(_("Requested keysize is %u bits\n"), nbits );
1088 if( algo == PUBKEY_ALGO_DSA && (nbits % 64) ) {
1089 nbits = ((nbits + 63) / 64) * 64;
1090 tty_printf(_("rounded up to %u bits\n"), nbits );
1092 else if( (nbits % 32) ) {
1093 nbits = ((nbits + 31) / 32) * 32;
1094 tty_printf(_("rounded up to %u bits\n"), nbits );
1101 * Parse an expire string and return it's value in days.
1102 * Returns -1 on error.
1105 parse_expire_string( const char *string )
1109 u32 curtime = make_timestamp();
1114 else if( (abs_date = scan_isodatestr(string)) && abs_date > curtime ) {
1115 /* This calculation is not perfectly okay because we
1116 * are later going to simply multiply by 86400 and don't
1117 * correct for leapseconds. A solution would be to change
1118 * the whole implemenation to work with dates and not intervals
1119 * which are required for v3 keys.
1121 valid_days = abs_date/86400-curtime/86400+1;
1123 else if( (mult=check_valid_days(string)) ) {
1124 valid_days = atoi(string) * mult;
1125 if( valid_days < 0 || valid_days > 39447 )
1134 /* object == 0 for a key, and 1 for a sig */
1136 ask_expire_interval(int object)
1145 tty_printf(_("Please specify how long the key should be valid.\n"
1146 " 0 = key does not expire\n"
1147 " <n> = key expires in n days\n"
1148 " <n>w = key expires in n weeks\n"
1149 " <n>m = key expires in n months\n"
1150 " <n>y = key expires in n years\n"));
1154 tty_printf(_("Please specify how long the signature should be valid.\n"
1155 " 0 = signature does not expire\n"
1156 " <n> = signature expires in n days\n"
1157 " <n>w = signature expires in n weeks\n"
1158 " <n>m = signature expires in n months\n"
1159 " <n>y = signature expires in n years\n"));
1166 /* Note: The elgamal subkey for DSA has no expiration date because
1167 * it must be signed with the DSA key and this one has the expiration
1172 u32 curtime=make_timestamp();
1176 answer = cpr_get("keygen.valid",_("Key is valid for? (0) "));
1178 answer = cpr_get("siggen.valid",_("Signature is valid for? (0) "));
1180 trim_spaces(answer);
1181 valid_days = parse_expire_string( answer );
1182 if( valid_days < 0 ) {
1183 tty_printf(_("invalid value\n"));
1188 tty_printf(_("%s does not expire at all\n"),
1189 object==0?"Key":"Signature");
1193 interval = valid_days * 86400L;
1194 /* print the date when the key expires */
1195 tty_printf(_("%s expires at %s\n"),
1196 object==0?"Key":"Signature",
1197 asctimestamp((ulong)(curtime + interval) ) );
1198 /* FIXME: This check yields warning on alhas:
1199 write a configure check and to this check here only for 32 bit machines */
1200 if( (time_t)((ulong)(curtime+interval)) < 0 )
1201 tty_printf(_("Your system can't display dates beyond 2038.\n"
1202 "However, it will be correctly handled up to 2106.\n"));
1205 if( cpr_enabled() || cpr_get_answer_is_yes("keygen.valid.okay",
1206 _("Is this correct (y/n)? ")) )
1216 u32 x = ask_expire_interval(0);
1217 return x? make_timestamp() + x : 0;
1221 has_invalid_email_chars( const char *s )
1224 static char valid_chars[] = "01234567890_-."
1225 "abcdefghijklmnopqrstuvwxyz"
1226 "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1233 else if( !at_seen && !( !!strchr( valid_chars, *s ) || *s == '+' ) )
1235 else if( at_seen && !strchr( valid_chars, *s ) )
1243 ask_user_id( int mode )
1246 char *aname, *acomment, *amail, *uid;
1250 "You need a User-ID to identify your key; the software constructs the user id\n"
1251 "from Real Name, Comment and Email Address in this form:\n"
1252 " \"Heinrich Heine (Der Dichter) <heinrichh@duesseldorf.de>\"\n\n") );
1253 uid = aname = acomment = amail = NULL;
1261 aname = cpr_get("keygen.name",_("Real name: "));
1265 if( opt.allow_freeform_uid )
1268 if( strpbrk( aname, "<>" ) )
1269 tty_printf(_("Invalid character in name\n"));
1270 else if( isdigit(*aname) )
1271 tty_printf(_("Name may not start with a digit\n"));
1272 else if( strlen(aname) < 5 )
1273 tty_printf(_("Name must be at least 5 characters long\n"));
1281 amail = cpr_get("keygen.email",_("Email address: "));
1285 break; /* no email address is okay */
1286 else if( has_invalid_email_chars(amail)
1287 || string_count_chr(amail,'@') != 1
1289 || amail[strlen(amail)-1] == '@'
1290 || amail[strlen(amail)-1] == '.'
1291 || strstr(amail, "..") )
1292 tty_printf(_("Not a valid email address\n"));
1300 acomment = cpr_get("keygen.comment",_("Comment: "));
1301 trim_spaces(acomment);
1304 break; /* no comment is okay */
1305 else if( strpbrk( acomment, "()" ) )
1306 tty_printf(_("Invalid character in comment\n"));
1314 uid = p = m_alloc(strlen(aname)+strlen(amail)+strlen(acomment)+12+10);
1315 p = stpcpy(p, aname );
1317 p = stpcpy(stpcpy(stpcpy(p," ("), acomment),")");
1319 p = stpcpy(stpcpy(stpcpy(p," <"), amail),">");
1321 /* append a warning if we do not have dev/random
1322 * or it is switched into quick testmode */
1323 if( quick_random_gen(-1) )
1324 strcpy(p, " (INSECURE!)" );
1326 /* print a note in case that UTF8 mapping has to be done */
1327 for(p=uid; *p; p++ ) {
1329 tty_printf(_("You are using the `%s' character set.\n"),
1330 get_native_charset() );
1335 tty_printf(_("You selected this USER-ID:\n \"%s\"\n\n"), uid);
1336 /* fixme: add a warning if this user-id already exists */
1337 if( !*amail && (strchr( aname, '@' ) || strchr( acomment, '@'))) {
1339 tty_printf(_("Please don't put the email address "
1340 "into the real name or the comment\n") );
1344 const char *ansstr = _("NnCcEeOoQq");
1346 if( strlen(ansstr) != 10 )
1348 if( cpr_enabled() ) {
1349 answer = m_strdup(ansstr+6);
1353 answer = cpr_get("keygen.userid.cmd", fail?
1354 _("Change (N)ame, (C)omment, (E)mail or (Q)uit? ") :
1355 _("Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? "));
1358 if( strlen(answer) > 1 )
1360 else if( *answer == ansstr[0] || *answer == ansstr[1] ) {
1361 m_free(aname); aname = NULL;
1364 else if( *answer == ansstr[2] || *answer == ansstr[3] ) {
1365 m_free(acomment); acomment = NULL;
1368 else if( *answer == ansstr[4] || *answer == ansstr[5] ) {
1369 m_free(amail); amail = NULL;
1372 else if( *answer == ansstr[6] || *answer == ansstr[7] ) {
1374 tty_printf(_("Please correct the error first\n"));
1377 m_free(aname); aname = NULL;
1378 m_free(acomment); acomment = NULL;
1379 m_free(amail); amail = NULL;
1383 else if( *answer == ansstr[8] || *answer == ansstr[9] ) {
1384 m_free(aname); aname = NULL;
1385 m_free(acomment); acomment = NULL;
1386 m_free(amail); amail = NULL;
1387 m_free(uid); uid = NULL;
1393 if( !amail && !acomment && !amail )
1395 m_free(uid); uid = NULL;
1398 char *p = native_to_utf8( uid );
1407 ask_passphrase( STRING2KEY **ret_s2k )
1411 const char *errtext = NULL;
1413 tty_printf(_("You need a Passphrase to protect your secret key.\n\n") );
1415 s2k = m_alloc_secure( sizeof *s2k );
1417 s2k->mode = opt.s2k_mode;
1418 s2k->hash_algo = opt.s2k_digest_algo;
1419 dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k,2,errtext);
1421 errtext = _("passphrase not correctly repeated; try again");
1422 tty_printf(_("%s.\n"), errtext);
1424 else if( !dek->keylen ) {
1425 m_free(dek); dek = NULL;
1426 m_free(s2k); s2k = NULL;
1428 "You don't want a passphrase - this is probably a *bad* idea!\n"
1429 "I will do it anyway. You can change your passphrase at any time,\n"
1430 "using this program with the option \"--edit-key\".\n\n"));
1442 do_create( int algo, unsigned int nbits, KBNODE pub_root, KBNODE sec_root,
1443 DEK *dek, STRING2KEY *s2k, PKT_secret_key **sk, u32 expiredate )
1449 "We need to generate a lot of random bytes. It is a good idea to perform\n"
1450 "some other action (type on the keyboard, move the mouse, utilize the\n"
1451 "disks) during the prime generation; this gives the random number\n"
1452 "generator a better chance to gain enough entropy.\n") );
1454 if( algo == PUBKEY_ALGO_ELGAMAL || algo == PUBKEY_ALGO_ELGAMAL_E )
1455 rc = gen_elg(algo, nbits, pub_root, sec_root, dek, s2k, sk, expiredate);
1456 else if( algo == PUBKEY_ALGO_DSA )
1457 rc = gen_dsa(nbits, pub_root, sec_root, dek, s2k, sk, expiredate);
1458 else if( algo == PUBKEY_ALGO_RSA )
1459 rc = gen_rsa(algo, nbits, pub_root, sec_root, dek, s2k, sk, expiredate);
1463 #ifdef ENABLE_COMMENT_PACKETS
1465 add_kbnode( pub_root,
1466 make_comment_node("#created by GNUPG v" VERSION " ("
1467 PRINTABLE_OS_NAME ")"));
1468 add_kbnode( sec_root,
1469 make_comment_node("#created by GNUPG v" VERSION " ("
1470 PRINTABLE_OS_NAME ")"));
1478 * Generate a new user id packet, or return NULL if canceled
1487 p = ask_user_id( 1 );
1491 uid = m_alloc_clear( sizeof *uid + n - 1 );
1493 strcpy(uid->name, p);
1500 release_parameter_list( struct para_data_s *r )
1502 struct para_data_s *r2;
1504 for( ; r ; r = r2 ) {
1506 if( r->key == pPASSPHRASE_DEK )
1508 else if( r->key == pPASSPHRASE_S2K )
1515 static struct para_data_s *
1516 get_parameter( struct para_data_s *para, enum para_name key )
1518 struct para_data_s *r;
1520 for( r = para; r && r->key != key; r = r->next )
1526 get_parameter_value( struct para_data_s *para, enum para_name key )
1528 struct para_data_s *r = get_parameter( para, key );
1529 return (r && *r->u.value)? r->u.value : NULL;
1533 get_parameter_algo( struct para_data_s *para, enum para_name key )
1536 struct para_data_s *r = get_parameter( para, key );
1539 if( isdigit( *r->u.value ) )
1540 i = atoi( r->u.value );
1542 i = string_to_pubkey_algo( r->u.value );
1543 if (i == PUBKEY_ALGO_RSA_E || i == PUBKEY_ALGO_RSA_S)
1544 i = 0; /* we don't want to allow generation of these algorithms */
1549 * parse the usage parameter and set the keyflags. Return true on error.
1552 parse_parameter_usage (const char *fname,
1553 struct para_data_s *para, enum para_name key)
1555 struct para_data_s *r = get_parameter( para, key );
1560 return 0; /* none (this is an optional parameter)*/
1564 while ( (p = strsep (&pn, " \t,")) ) {
1567 else if ( !ascii_strcasecmp (p, "sign") )
1568 use |= PUBKEY_USAGE_SIG;
1569 else if ( !ascii_strcasecmp (p, "encrypt") )
1570 use |= PUBKEY_USAGE_ENC;
1572 log_error("%s:%d: invalid usage list\n", fname, r->lnr );
1573 return -1; /* error */
1581 parse_revocation_key (const char *fname,
1582 struct para_data_s *para, enum para_name key)
1584 struct para_data_s *r = get_parameter( para, key );
1585 struct revocation_key revkey;
1590 return 0; /* none (this is an optional parameter) */
1595 revkey.algid=atoi(pn);
1599 /* Skip to the fpr */
1600 while(*pn && *pn!=':')
1608 for(i=0;i<MAX_FINGERPRINT_LEN && *pn;i++,pn+=2)
1610 int c=hextobyte(pn);
1617 /* skip to the tag */
1618 while(*pn && *pn!='s' && *pn!='S')
1621 if(ascii_strcasecmp(pn,"sensitive")==0)
1624 memcpy(&r->u.revkey,&revkey,sizeof(struct revocation_key));
1629 log_error("%s:%d: invalid revocation key\n", fname, r->lnr );
1630 return -1; /* error */
1635 get_parameter_u32( struct para_data_s *para, enum para_name key )
1637 struct para_data_s *r = get_parameter( para, key );
1641 if( r->key == pKEYEXPIRE || r->key == pSUBKEYEXPIRE )
1643 if( r->key == pKEYUSAGE || r->key == pSUBKEYUSAGE )
1646 return (unsigned int)strtoul( r->u.value, NULL, 10 );
1650 get_parameter_uint( struct para_data_s *para, enum para_name key )
1652 return get_parameter_u32( para, key );
1656 get_parameter_dek( struct para_data_s *para, enum para_name key )
1658 struct para_data_s *r = get_parameter( para, key );
1659 return r? r->u.dek : NULL;
1663 get_parameter_s2k( struct para_data_s *para, enum para_name key )
1665 struct para_data_s *r = get_parameter( para, key );
1666 return r? r->u.s2k : NULL;
1669 static struct revocation_key *
1670 get_parameter_revkey( struct para_data_s *para, enum para_name key )
1672 struct para_data_s *r = get_parameter( para, key );
1673 return r? &r->u.revkey : NULL;
1677 proc_parameter_file( struct para_data_s *para, const char *fname,
1678 struct output_control_s *outctrl )
1680 struct para_data_s *r;
1681 const char *s1, *s2, *s3;
1686 /* check that we have all required parameters */
1687 assert( get_parameter( para, pKEYTYPE ) );
1688 i = get_parameter_algo( para, pKEYTYPE );
1689 if( i < 1 || check_pubkey_algo2( i, PUBKEY_USAGE_SIG ) ) {
1690 r = get_parameter( para, pKEYTYPE );
1691 log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
1695 if (parse_parameter_usage (fname, para, pKEYUSAGE))
1698 i = get_parameter_algo( para, pSUBKEYTYPE );
1699 if( i > 0 && check_pubkey_algo( i ) ) {
1700 r = get_parameter( para, pSUBKEYTYPE );
1701 log_error("%s:%d: invalid algorithm\n", fname, r->lnr );
1704 if (i > 0 && parse_parameter_usage (fname, para, pSUBKEYUSAGE))
1708 if( !get_parameter_value( para, pUSERID ) ) {
1709 /* create the formatted user ID */
1710 s1 = get_parameter_value( para, pNAMEREAL );
1711 s2 = get_parameter_value( para, pNAMECOMMENT );
1712 s3 = get_parameter_value( para, pNAMEEMAIL );
1713 if( s1 || s2 || s3 ) {
1714 n = (s1?strlen(s1):0) + (s2?strlen(s2):0) + (s3?strlen(s3):0);
1715 r = m_alloc_clear( sizeof *r + n + 20 );
1721 p = stpcpy(stpcpy(stpcpy(p," ("), s2 ),")");
1723 p = stpcpy(stpcpy(stpcpy(p," <"), s3 ),">");
1729 /* Set preferences, if any. */
1730 keygen_set_std_prefs(get_parameter_value( para, pPREFERENCES ), 0);
1732 /* Set revoker, if any. */
1733 if (parse_revocation_key (fname, para, pREVOKER))
1736 /* make DEK and S2K from the Passphrase */
1737 r = get_parameter( para, pPASSPHRASE );
1738 if( r && *r->u.value ) {
1739 /* we have a plain text passphrase - create a DEK from it.
1740 * It is a little bit ridiculous to keep it ih secure memory
1741 * but becuase we do this alwasy, why not here */
1745 s2k = m_alloc_secure( sizeof *s2k );
1746 s2k->mode = opt.s2k_mode;
1747 s2k->hash_algo = opt.s2k_digest_algo;
1748 set_next_passphrase( r->u.value );
1749 dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k, 2, NULL );
1750 set_next_passphrase( NULL );
1752 memset( r->u.value, 0, strlen(r->u.value) );
1754 r = m_alloc_clear( sizeof *r );
1755 r->key = pPASSPHRASE_S2K;
1759 r = m_alloc_clear( sizeof *r );
1760 r->key = pPASSPHRASE_DEK;
1766 /* make KEYEXPIRE from Expire-Date */
1767 r = get_parameter( para, pEXPIREDATE );
1768 if( r && *r->u.value ) {
1769 i = parse_expire_string( r->u.value );
1771 log_error("%s:%d: invalid expire date\n", fname, r->lnr );
1774 r->u.expire = i * 86400L;
1775 r->key = pKEYEXPIRE; /* change hat entry */
1776 /* also set it for the subkey */
1777 r = m_alloc_clear( sizeof *r + 20 );
1778 r->key = pSUBKEYEXPIRE;
1779 r->u.expire = i * 86400L;
1784 if( !!outctrl->pub.newfname ^ !!outctrl->sec.newfname ) {
1785 log_error("%s:%d: only one ring name is set\n", fname, outctrl->lnr );
1789 do_generate_keypair( para, outctrl );
1795 * Kludge to allow non interactive key generation controlled
1796 * by a parameter file (which currently is only stdin)
1797 * Note, that string parameters are expected to be in UTF-8
1800 read_parameter_file( const char *fname )
1802 static struct { const char *name;
1805 { "Key-Type", pKEYTYPE},
1806 { "Key-Length", pKEYLENGTH },
1807 { "Key-Usage", pKEYUSAGE },
1808 { "Subkey-Type", pSUBKEYTYPE },
1809 { "Subkey-Length", pSUBKEYLENGTH },
1810 { "Subkey-Usage", pSUBKEYUSAGE },
1811 { "Name-Real", pNAMEREAL },
1812 { "Name-Email", pNAMEEMAIL },
1813 { "Name-Comment", pNAMECOMMENT },
1814 { "Expire-Date", pEXPIREDATE },
1815 { "Passphrase", pPASSPHRASE },
1816 { "Preferences", pPREFERENCES },
1817 { "Revoker", pREVOKER },
1821 char line[1024], *p;
1823 const char *err = NULL;
1824 struct para_data_s *para, *r;
1826 struct output_control_s outctrl;
1828 memset( &outctrl, 0, sizeof( outctrl ) );
1830 if( !fname || !*fname || !strcmp(fname,"-") ) {
1835 fp = fopen( fname, "r" );
1837 log_error(_("can't open `%s': %s\n"), fname, strerror(errno) );
1845 while( fgets( line, DIM(line)-1, fp ) ) {
1846 char *keyword, *value;
1849 if( *line && line[strlen(line)-1] != '\n' ) {
1850 err = "line too long";
1853 for( p = line; isspace(*(byte*)p); p++ )
1855 if( !*p || *p == '#' )
1858 if( *keyword == '%' ) {
1859 for( ; !isspace(*(byte*)p); p++ )
1863 for( ; isspace(*(byte*)p); p++ )
1866 trim_trailing_ws( value, strlen(value) );
1867 if( !ascii_strcasecmp( keyword, "%echo" ) )
1868 log_info("%s\n", value );
1869 else if( !ascii_strcasecmp( keyword, "%dry-run" ) )
1871 else if( !ascii_strcasecmp( keyword, "%commit" ) ) {
1873 proc_parameter_file( para, fname, &outctrl );
1874 release_parameter_list( para );
1877 else if( !ascii_strcasecmp( keyword, "%pubring" ) ) {
1878 if( outctrl.pub.fname && !strcmp( outctrl.pub.fname, value ) )
1879 ; /* still the same file - ignore it */
1881 m_free( outctrl.pub.newfname );
1882 outctrl.pub.newfname = m_strdup( value );
1883 outctrl.use_files = 1;
1886 else if( !ascii_strcasecmp( keyword, "%secring" ) ) {
1887 if( outctrl.sec.fname && !strcmp( outctrl.sec.fname, value ) )
1888 ; /* still the same file - ignore it */
1890 m_free( outctrl.sec.newfname );
1891 outctrl.sec.newfname = m_strdup( value );
1892 outctrl.use_files = 1;
1896 log_info("skipping control `%s' (%s)\n", keyword, value );
1903 if( !(p = strchr( p, ':' )) || p == keyword ) {
1904 err = "missing colon";
1909 for( ; isspace(*(byte*)p); p++ )
1912 err = "missing argument";
1916 trim_trailing_ws( value, strlen(value) );
1918 for(i=0; keywords[i].name; i++ ) {
1919 if( !ascii_strcasecmp( keywords[i].name, keyword ) )
1922 if( !keywords[i].name ) {
1923 err = "unknown keyword";
1926 if( keywords[i].key != pKEYTYPE && !para ) {
1927 err = "parameter block does not start with \"Key-Type\"";
1931 if( keywords[i].key == pKEYTYPE && para ) {
1933 proc_parameter_file( para, fname, &outctrl );
1934 release_parameter_list( para );
1938 for( r = para; r; r = r->next ) {
1939 if( r->key == keywords[i].key )
1943 err = "duplicate keyword";
1947 r = m_alloc_clear( sizeof *r + strlen( value ) );
1949 r->key = keywords[i].key;
1950 strcpy( r->u.value, value );
1955 log_error("%s:%d: %s\n", fname, lnr, err );
1956 else if( ferror(fp) ) {
1957 log_error("%s:%d: read error: %s\n", fname, lnr, strerror(errno) );
1961 proc_parameter_file( para, fname, &outctrl );
1964 if( outctrl.use_files ) { /* close open streams */
1965 iobuf_close( outctrl.pub.stream );
1966 iobuf_close( outctrl.sec.stream );
1967 m_free( outctrl.pub.fname );
1968 m_free( outctrl.pub.newfname );
1969 m_free( outctrl.sec.fname );
1970 m_free( outctrl.sec.newfname );
1973 release_parameter_list( para );
1974 if( strcmp( fname, "-" ) )
1980 * Generate a keypair
1981 * (fname is only used in batch mode)
1984 generate_keypair( const char *fname )
1994 struct para_data_s *para = NULL;
1995 struct para_data_s *r;
1996 struct output_control_s outctrl;
1998 memset( &outctrl, 0, sizeof( outctrl ) );
2001 read_parameter_file( fname );
2005 algo = ask_algo( 0, &use );
2006 if( !algo ) { /* default: DSA with ElG subkey of the specified size */
2008 r = m_alloc_clear( sizeof *r + 20 );
2010 sprintf( r->u.value, "%d", PUBKEY_ALGO_DSA );
2013 tty_printf(_("DSA keypair will have 1024 bits.\n"));
2014 r = m_alloc_clear( sizeof *r + 20 );
2015 r->key = pKEYLENGTH;
2016 strcpy( r->u.value, "1024" );
2020 algo = PUBKEY_ALGO_ELGAMAL_E;
2021 r = m_alloc_clear( sizeof *r + 20 );
2022 r->key = pSUBKEYTYPE;
2023 sprintf( r->u.value, "%d", algo );
2028 r = m_alloc_clear( sizeof *r + 20 );
2030 sprintf( r->u.value, "%d", algo );
2035 r = m_alloc_clear( sizeof *r + 20 );
2037 sprintf( r->u.value, "%s%s",
2038 (use & PUBKEY_USAGE_SIG)? "sign ":"",
2039 (use & PUBKEY_USAGE_ENC)? "encrypt ":"" );
2046 nbits = ask_keysize( algo );
2047 r = m_alloc_clear( sizeof *r + 20 );
2048 r->key = both? pSUBKEYLENGTH : pKEYLENGTH;
2049 sprintf( r->u.value, "%u", nbits);
2053 expire = ask_expire_interval(0);
2054 r = m_alloc_clear( sizeof *r + 20 );
2055 r->key = pKEYEXPIRE;
2056 r->u.expire = expire;
2059 r = m_alloc_clear( sizeof *r + 20 );
2060 r->key = pSUBKEYEXPIRE;
2061 r->u.expire = expire;
2065 uid = ask_user_id(0);
2067 log_error(_("Key generation canceled.\n"));
2068 release_parameter_list( para );
2071 r = m_alloc_clear( sizeof *r + strlen(uid) );
2073 strcpy( r->u.value, uid );
2077 dek = ask_passphrase( &s2k );
2079 r = m_alloc_clear( sizeof *r );
2080 r->key = pPASSPHRASE_DEK;
2084 r = m_alloc_clear( sizeof *r );
2085 r->key = pPASSPHRASE_S2K;
2091 proc_parameter_file( para, "[internal]", &outctrl );
2092 release_parameter_list( para );
2097 print_status_key_created (int letter, PKT_public_key *pk)
2099 byte array[MAX_FINGERPRINT_LEN], *s;
2100 char buf[MAX_FINGERPRINT_LEN*2+30], *p;
2106 fingerprint_from_pk (pk, array, &n);
2108 for (i=0; i < n ; i++, s++, p += 2)
2109 sprintf (p, "%02X", *s);
2111 write_status_text (STATUS_KEY_CREATED, buf);
2115 do_generate_keypair( struct para_data_s *para,
2116 struct output_control_s *outctrl )
2118 KBNODE pub_root = NULL;
2119 KBNODE sec_root = NULL;
2120 PKT_secret_key *sk = NULL;
2122 struct revocation_key *revkey;
2126 if( outctrl->dryrun ) {
2127 log_info("dry-run mode - key generation skipped\n");
2132 if( outctrl->use_files ) {
2133 if( outctrl->pub.newfname ) {
2134 iobuf_close(outctrl->pub.stream);
2135 outctrl->pub.stream = NULL;
2136 m_free( outctrl->pub.fname );
2137 outctrl->pub.fname = outctrl->pub.newfname;
2138 outctrl->pub.newfname = NULL;
2140 outctrl->pub.stream = iobuf_create( outctrl->pub.fname );
2141 if( !outctrl->pub.stream ) {
2142 log_error("can't create `%s': %s\n", outctrl->pub.newfname,
2147 outctrl->pub.afx.what = 1;
2148 iobuf_push_filter( outctrl->pub.stream, armor_filter,
2149 &outctrl->pub.afx );
2152 if( outctrl->sec.newfname ) {
2153 iobuf_close(outctrl->sec.stream);
2154 outctrl->sec.stream = NULL;
2155 m_free( outctrl->sec.fname );
2156 outctrl->sec.fname = outctrl->sec.newfname;
2157 outctrl->sec.newfname = NULL;
2159 outctrl->sec.stream = iobuf_create( outctrl->sec.fname );
2160 if( !outctrl->sec.stream ) {
2161 log_error("can't create `%s': %s\n", outctrl->sec.newfname,
2166 outctrl->sec.afx.what = 5;
2167 iobuf_push_filter( outctrl->sec.stream, armor_filter,
2168 &outctrl->sec.afx );
2171 assert( outctrl->pub.stream );
2172 assert( outctrl->sec.stream );
2174 log_info(_("writing public key to `%s'\n"), outctrl->pub.fname );
2175 log_info(_("writing secret key to `%s'\n"), outctrl->sec.fname );
2180 /* we create the packets as a tree of kbnodes. Because the structure
2181 * we create is known in advance we simply generate a linked list
2182 * The first packet is a dummy comment packet which we flag
2183 * as deleted. The very first packet must always be a KEY packet.
2185 pub_root = make_comment_node("#"); delete_kbnode(pub_root);
2186 sec_root = make_comment_node("#"); delete_kbnode(sec_root);
2188 rc = do_create( get_parameter_algo( para, pKEYTYPE ),
2189 get_parameter_uint( para, pKEYLENGTH ),
2191 get_parameter_dek( para, pPASSPHRASE_DEK ),
2192 get_parameter_s2k( para, pPASSPHRASE_S2K ),
2194 get_parameter_u32( para, pKEYEXPIRE ) );
2196 if(!rc && (revkey=get_parameter_revkey(para,pREVOKER)))
2198 rc=write_direct_sig(pub_root,pub_root,sk,revkey);
2200 write_direct_sig(sec_root,pub_root,sk,revkey);
2203 if( !rc && (s=get_parameter_value(para, pUSERID)) ) {
2204 write_uid(pub_root, s );
2206 write_uid(sec_root, s );
2208 rc = write_selfsig(pub_root, pub_root, sk,
2209 get_parameter_uint (para, pKEYUSAGE));
2211 rc = write_selfsig(sec_root, pub_root, sk,
2212 get_parameter_uint (para, pKEYUSAGE));
2215 if( get_parameter( para, pSUBKEYTYPE ) ) {
2216 rc = do_create( get_parameter_algo( para, pSUBKEYTYPE ),
2217 get_parameter_uint( para, pSUBKEYLENGTH ),
2219 get_parameter_dek( para, pPASSPHRASE_DEK ),
2220 get_parameter_s2k( para, pPASSPHRASE_S2K ),
2222 get_parameter_u32( para, pSUBKEYEXPIRE ) );
2224 rc = write_keybinding(pub_root, pub_root, sk,
2225 get_parameter_uint (para, pSUBKEYUSAGE));
2227 rc = write_keybinding(sec_root, pub_root, sk,
2228 get_parameter_uint (para, pSUBKEYUSAGE));
2233 if( !rc && outctrl->use_files ) { /* direct write to specified files */
2234 rc = write_keyblock( outctrl->pub.stream, pub_root );
2236 log_error("can't write public key: %s\n", g10_errstr(rc) );
2238 rc = write_keyblock( outctrl->sec.stream, sec_root );
2240 log_error("can't write secret key: %s\n", g10_errstr(rc) );
2244 else if( !rc ) { /* write to the standard keyrings */
2245 KEYDB_HANDLE pub_hd = keydb_new (0);
2246 KEYDB_HANDLE sec_hd = keydb_new (1);
2248 /* FIXME: we may have to create the keyring first */
2249 rc = keydb_locate_writable (pub_hd, NULL);
2251 log_error (_("no writable public keyring found: %s\n"),
2255 rc = keydb_locate_writable (sec_hd, NULL);
2257 log_error (_("no writable secret keyring found: %s\n"),
2261 if (!rc && opt.verbose) {
2262 log_info(_("writing public key to `%s'\n"),
2263 keydb_get_resource_name (pub_hd));
2264 log_info(_("writing secret key to `%s'\n"),
2265 keydb_get_resource_name (sec_hd));
2269 rc = keydb_insert_keyblock (pub_hd, pub_root);
2271 log_error (_("error writing public keyring `%s': %s\n"),
2272 keydb_get_resource_name (pub_hd), g10_errstr(rc));
2276 rc = keydb_insert_keyblock (sec_hd, sec_root);
2278 log_error (_("error writing secret keyring `%s': %s\n"),
2279 keydb_get_resource_name (pub_hd), g10_errstr(rc));
2282 keydb_release (pub_hd);
2283 keydb_release (sec_hd);
2287 get_parameter_algo(para, pKEYTYPE) == PUBKEY_ALGO_RSA
2288 && get_parameter_uint( para, pKEYUSAGE )
2289 && !(get_parameter_uint( para,pKEYUSAGE) & PUBKEY_USAGE_ENC);
2290 PKT_public_key *pk = find_kbnode (pub_root,
2291 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
2293 update_ownertrust (pk,
2294 ((get_ownertrust (pk) & ~TRUST_MASK)
2295 | TRUST_ULTIMATE ));
2298 tty_printf(_("public and secret key created and signed.\n") );
2299 tty_printf(_("key marked as ultimately trusted.\n") );
2301 list_keyblock(pub_root,0,1,NULL);
2306 && ( get_parameter_algo( para, pKEYTYPE ) == PUBKEY_ALGO_DSA
2308 && !get_parameter( para, pSUBKEYTYPE ) )
2310 tty_printf(_("Note that this key cannot be used for "
2311 "encryption. You may want to use\n"
2312 "the command \"--edit-key\" to generate a "
2313 "secondary key for this purpose.\n") );
2320 log_error("key generation failed: %s\n", g10_errstr(rc) );
2322 tty_printf(_("Key generation failed: %s\n"), g10_errstr(rc) );
2325 PKT_public_key *pk = find_kbnode (pub_root,
2326 PKT_PUBLIC_KEY)->pkt->pkt.public_key;
2327 print_status_key_created (did_sub? 'B':'P', pk);
2329 release_kbnode( pub_root );
2330 release_kbnode( sec_root );
2331 if( sk ) /* the unprotected secret key */
2332 free_secret_key(sk);
2337 * add a new subkey to an existing key.
2338 * Returns true if a new key has been generated and put into the keyblocks.
2341 generate_subkeypair( KBNODE pub_keyblock, KBNODE sec_keyblock )
2345 PKT_secret_key *sk = NULL; /* this is the primary sk */
2350 char *passphrase = NULL;
2352 STRING2KEY *s2k = NULL;
2355 /* break out the primary secret key */
2356 node = find_kbnode( sec_keyblock, PKT_SECRET_KEY );
2358 log_error("Oops; secret key not found anymore!\n");
2362 /* make a copy of the sk to keep the protected one in the keyblock */
2363 sk = copy_secret_key( NULL, node->pkt->pkt.secret_key );
2365 cur_time = make_timestamp();
2366 if( sk->timestamp > cur_time ) {
2367 ulong d = sk->timestamp - cur_time;
2368 log_info( d==1 ? _("key has been created %lu second "
2369 "in future (time warp or clock problem)\n")
2370 : _("key has been created %lu seconds "
2371 "in future (time warp or clock problem)\n"), d );
2372 if( !opt.ignore_time_conflict ) {
2373 rc = G10ERR_TIME_CONFLICT;
2378 if (sk->version < 4) {
2379 log_info (_("NOTE: creating subkeys for v3 keys "
2380 "is not OpenPGP compliant\n"));
2384 /* unprotect to get the passphrase */
2385 switch( is_secret_key_protected( sk ) ) {
2387 rc = G10ERR_PUBKEY_ALGO;
2390 tty_printf("This key is not protected.\n");
2393 tty_printf("Key is protected.\n");
2394 rc = check_secret_key( sk, 0 );
2396 passphrase = get_last_passphrase();
2403 algo = ask_algo( 1, &use );
2405 nbits = ask_keysize( algo );
2406 expire = ask_expire_interval(0);
2407 if( !cpr_enabled() && !cpr_get_answer_is_yes("keygen.sub.okay",
2408 _("Really create? ") ) )
2412 s2k = m_alloc_secure( sizeof *s2k );
2413 s2k->mode = opt.s2k_mode;
2414 s2k->hash_algo = opt.s2k_digest_algo;
2415 set_next_passphrase( passphrase );
2416 dek = passphrase_to_dek( NULL, 0, opt.s2k_cipher_algo, s2k, 2, NULL );
2419 rc = do_create( algo, nbits, pub_keyblock, sec_keyblock,
2420 dek, s2k, NULL, expire );
2422 rc = write_keybinding(pub_keyblock, pub_keyblock, sk, use);
2424 rc = write_keybinding(sec_keyblock, pub_keyblock, sk, use);
2427 write_status_text (STATUS_KEY_CREATED, "S");
2432 log_error(_("Key generation failed: %s\n"), g10_errstr(rc) );
2433 m_free( passphrase );
2436 if( sk ) /* release the copy of the (now unprotected) secret key */
2437 free_secret_key(sk);
2438 set_next_passphrase( NULL );
2443 * Write a keyblock to an output stream
2446 write_keyblock( IOBUF out, KBNODE node )
2448 for( ; node ; node = node->next ) {
2449 int rc = build_packet( out, node->pkt );
2451 log_error("build_packet(%d) failed: %s\n",
2452 node->pkt->pkttype, g10_errstr(rc) );
2453 return G10ERR_WRITE_FILE;